Reputation: 31
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
}
}
Upvotes: 0
Views: 331
Reputation: 347334
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)
Upvotes: 7