Reputation: 11
// Driver Code
public static void main(String[] args) {
int test = 3;
printFun(test);
}
static void printFun(int test) {
if (test < 1)
return;
else {
System.out.printf("%d ", test);
printFun(test - 1); // statement 2
System.out.printf("%d ", test);
return;
}
}
In this piece of code taken from GeeksforGeeks. There is something that I couldn't understand, It writes 3 2 1 1 2 3
and the recursive function is allocated in stacks. So it calls the statement2
before the second printf
, does this mean it firstly writes the recursive function and skips the second printf
until the base case is satisfied and then prints the second printf
. I couldn't completely understand the order.
Upvotes: 0
Views: 163
Reputation: 186
The output is 3 2 1 1 2 3 , the 3 2 1 getting printed as a part of first System.out.println() statement.
1 2 3 is getting printed as the part of second System.out.println() statement.
Upvotes: 0
Reputation: 7403
When you call a function, the function runs to completion, then returns. This is the same in a recursive use case, each call completes before returning. But of course each completion means calling another time the same function with a different stack. So this is what happens, in pseudo code:
printFun(3)
print 3
call printfun(2)
print 2
call printfun(1)
print 1
call printfun(0)
return
print 1
return
print 2
return
print 3
return
Upvotes: 3