1

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);
  }
}
0

6 Answers 6

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note: This is an implementation that follows similar sort of code that you had, so it does contain a trailing space (this means it'll output what you're looking for but will contain an extra space like such "0 1 2 3 4 5 4 3 2 1 0 " - note the extra space after the last 0). It is worth you taking a shot at trying to remove that yourself just so you can get a better grasp.
1

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

1 Comment

argument to print function should be 5, not 0. If i pass 7, then output should be 0 1 2 3 4 5 6 7 6 5 4 3 2 1 0
0

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);
}

Comments

0

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

Comments

0
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);
}

2 Comments

How would one initially invoke this method? Perhaps recursion(0, 5, 5) ?
@Abra I provided some examples of the initial invocation in an edit
0

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);
}

2 Comments

argument to foo function should be 5, not 0. If i pass 7, then output should be 0 1 2 3 4 5 6 7 6 5 4 3 2 1 0
I added an alternative method. The problem is that there is no termination value when supplied with an arbitrary number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.