0
votes

I am having trouble understanding recursion. I understand the theory. Like when a function calls itself, needs a base case to end the recursion and all that but when it comes to using it in a program, I get really confused. For example, I have posted some code below. When I call print function before the recursive function..it prints the numbers in reverse order (54321) and when I call it after the recursion, it prints it as 12345. Why is that?

public class Main {

    public static void main(String[] args) {

        printNumbers(5);
    }

    public static void printNumbers(int num){
        if(num==0) {
            return;
        }
       System.out.println(num); // this prints 54321

        printNumbers(num-1);
       System.out.println(num);//this prints 12345

    }
}
1
This is where something like a "desk check" would really help, start with a piece of paper and sketch out the state on each call - MadProgrammer
i did...so when i call printNumbers(num-1)...it will push printNumbers(4) onto the stack, next time it will push printNumbers(3) onto the stack untill it reaches 0..after which it will stop because of the case...at the end of our recursion our stack frame would have printNumbers(1) on the top...so shouldn't the first call print 12345? instead of 54321? since stack is a last in first out structure? - vaish
No, each time you "pop" (or return) for printNumbers it will return to the place it was called from, meaning that you get the numbers in reverse order from the way they were pushed - MadProgrammer
use a debugger and breakpoints - baao

1 Answers

7
votes

This is where something like a "desk check" (pen and paper) will come in very handy so you can step through the code and describe the state at each step.

Essentially, the second print statement won't get called until the printNumbers method returns, meaning that your execution looks something like...

printNumber(5)
    num = 5
    num == 0 = false
    print num (5)
    printNumbers(num - 1)
        num = 4
        num == 0 = false
        print num (4)
        printNumbers(num - 1)
            num = 3
            num == 0 = false
            print num (3)
            printNumbers(num - 1)
                num = 2
                num == 0 = false
                print num (2)
                printNumbers(num - 1)
                    num = 1
                    num == 0 = false
                    print num (1)
                    printNumbers(num - 1)
                        num = 0
                        num == 0 = true (return)
                    print num (1)
                print num (2)
            print num (3)
        print num (4)
    print num (5)