0

I want to print entered numbers as symmetric sequences without zero using recursive functions.

Let's take a method called void demo(int n).

Example

For n=5 it should print:

"5 4 3 2 1 2 3 4 5 "

Problem

I can print "5 4 3 2 1 ".

My recursive function is demo(n-1) so I can print. When function reached to n=0, I think it must redound the values. But I couldn't write anything inside of the if block.

Code

public class demo {

    void demo(int n) {
        if ( n == 0) 
        {
            // tried to write something here         
        }
        System.out.println(n);
        return demo(n-1);   
    }
}

How can I solve it?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
  • 1
    Possible duplicate of [using recursion to print symmetric integer sequences that count down and then up](http://stackoverflow.com/questions/14823511/using-recursion-to-print-symmetric-integer-sequences-that-count-down-and-then-up) – rb612 Jan 05 '16 at 01:50
  • Can you write the full solution? – Timuçin Çiçek Jan 05 '16 at 01:54

2 Answers2

1

This is what I would do:

public class demo {
    void demo(int n) {
        System.out.println(n);

        if (n > 1) {
            demo(n - 1);
            System.out.println(n);
        }
    }
}

It's not tail recursive, but this is a case where recursion is simpler than iteration.

If you iterate then you would need two loops:

  1. One loop counting down from n to 1.
  2. Another loop counting up from 2 to n.

However, using recursion we can simply count down from n to 1 and print each number and then print the number again after the recursion.

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
0

I find generally easier to directly tackle the end condition at the beginning of the recursive function, then perform the right processing.

public class demo {
    void demo(int n) {
        // displays the number once then goes back forward
        if(n <= 1) {
            System.out.print(n + " ");
            return;
        }    
        
        // displays the number once, then all the numbers below it, then again the number
        System.out.print(n + " ");
        demo(n - 1);
        System.out.print(n + " ");
    }
}

My solution is basically the reversed version of the accepted one, but I would say that it is clearer in a recursive context to actually handle the end condition with a return rather than continuing the processing while a condition remains true.