Search code examples
javarecursionnumberssymmetric

Recursively printing numbers as symmetric sequences


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?


Solution

  • 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.