user7500403
user7500403

Reputation:

Printing sequence of numbers via recursion

I want to print following sequence of numbers 0 1 2 3 4 5 4 3 2 1 0 using recurstion

What i have tried so far produces following sequence 0 1 2 3 4 5. What i can't figure out is how to print remaining sequence.

How can i achieve the desired output?

Code

class Main {
  public static void foo(int num) {
    if (num == 0) {
      System.out.print(num + " ");
      return;
    }

    foo(num - 1);

    System.out.print(num + " ");
  }

  public static void main(String[] args) {
    Main.foo(5);
  }
}

Upvotes: 1

Views: 339

Answers (6)

WJS
WJS

Reputation: 40024

To respond just to your question, you can do it like this.

Call it

foo(0);

And the method

public static void foo(int a) {
         if (a > 5) {
             return;
         } 
         prints 0 thru 5 ascending    
         System.out.println(a);
         // once 5 is printed, don't print it again)
         if (a == 5) {
             return;
         }
         // bump a by 1
         foo(a+1);
         // A the calls to foo return the older versions of
         // the variable `a` reappear from the stack.  But 5
         // was skipped.  So it's just
         //printing 4 thru 0 descending
         System.out.println(a);
    }

Alternative method (slight different calling with a termination value included)

public static void main(String[] args) {
   foo(5,5);
}

public static void foo(int a, int b) {
    System.out.println(b-a);
    if (a != 0) {
        foo(a-1,b);
        System.out.println(b-a);
    }
}

It could be invoked as follows to more closely meet your requirement.

foo(5);

public static void foo(int b) {
   foo(b,b);
}

Upvotes: 0

0xh3xa
0xh3xa

Reputation: 4859

NO need to using iteration number

     public static void print(int num) {
        if (num >= 5) {
            System.out.print(num + " ");
            return;
        }
        System.out.print(num + " ");
        print(num + 1);
        System.out.print(num + " ");
    }

    public static void main(String[] args) {
        print(0);
    }

, output

0 1 2 3 4 5 4 3 2 1 0

Upvotes: 1

loganrussell48
loganrussell48

Reputation: 1864

public static void recursion(int lo, int current, int hi){
        if(current != hi){
            System.out.printf("%d ", current);
            recursion(lo, current+1, hi);
        }
        System.out.printf("%d%c", current, current == lo ? '\n' : ' ');
    }

This method can print out an string of numbers like yours. It needs the starting point (lo), the current position in the list(current), and the maximum number(hi).

The recursive base case(when we don't want to use recursion anymore) is when current == hi. We print out the number, then return.

All other values print current, recurse, then print again after recursion is done.

This solution has the added benefit of printing a space after each char except after the final number. No trailing space :)

Initial invocation of this method would be like so:

recursion(0, 0, 5); //prints 0 -> 5 -> 0
recursion(0, 5, 5); //prints 5 -> 0
recursion(0, 1, 5); //prints 1 -> 5 -> 0
recursion(0, 6, 5); //counts up forever and eventually crashes

Some helpful method to make calling simpler for common uses, you could do something like this:

public static void countUpFromZeroDownToZero(int max){
    recursion(0, 0, max);
}

public static void countFromXToYToX(int lo, int hi){
    recursion(lo, lo, hi);
}

Upvotes: 0

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

One solution can be the following:

public class Main {
       public static void main (String[] args) {
          Main.foo(5, 5);
      }

      public static void foo(int num, int th) {
        if (num == 0) {
          System.out.print(num + " ");
          return;
        }
        if ( num == 1) {
          System.out.print(th + " ");
          System.out.print((th - num) + " ");
          return;
        }
        System.out.print(( th - num) + " ");
        foo(num - 1, th);
        System.out.print((th - num) + " ");
    }
  }

Here is an IDEONE link https://ideone.com/9U44NX

Upvotes: 0

LentilSoup
LentilSoup

Reputation: 97

Here's a possible way to do it. In a lot of cases with recursion you might find that introducing a "helper" method that the original method calls can help you achieve what you want when the original with just that one argument num might make it difficult to:

public class Main
{
    public static void foo(int num) {
        helper(num, 0);
    }

    private static void helper(int num, int count) {
        if (count == num) {
            System.out.print(count + " ");
        } else {
            System.out.print(count + " ");
            helper(num, count + 1);
            System.out.print(count + " ");
        }
    }

    public static void main(String[] args) {
        Main.foo(5);
    }
}

Upvotes: 1

cegredev
cegredev

Reputation: 1579

Not exactly clean, but gets the job done:

public static void main(String[] args) {
    printPattern(5);
}

public static void printPattern(int stop) {
    printPattern(0, stop, 1, false);
}

public static void printPattern(int n, int stop, int dir, boolean turnedAround) {
    System.out.println(n);

    if (n == stop) {
        if (turnedAround)
            return;

        printPattern(n - dir, 0, -dir, true);
    } else
        printPattern(n + dir, stop, dir, turnedAround);
}

Upvotes: 0

Related Questions