Reputation: 45
I am learning Java and in one of the recursion example the following code is used and I am not getting that why the print statement starts printing j from 1 instead of 10?
class Test {
void printtest(int j) {
if(j==0)
return;
else
printtest(j-1);
System.out.println(j);
}
}
public class RecursionTest {
public static void main(String args[]) {
Test t = new Test();
t.printtest(10);
}
}
Output:
1
2
3
4
......10
Upvotes: 2
Views: 83
Reputation: 11
The answer is because you put the System.out.println(j); under the function or method call, like this:
printtest(j-1);
System.out.println(j);
which will produce the following result:
1
2
.
.
.
10
but what if you change the position of System.out.println(j); to be above the function call like this:
System.out.println(j);
printtest(j-1);
it will produce the following result:
10
9
.
.
.
1
now I want you to try this code and see the result
System.out.println(j);
printtest(j-1);
System.out.println(j);
Upvotes: 0
Reputation: 59641
It depends on the order of your statements in the recursive method.
You have
printtest(j-1);
System.out.println(j);
This will first call the method, call the method, call the method ... and then print, return from the method, print, return from the method, print ...
You can change that to
System.out.println(j);
printtest(j-1);
which will print, call the method, print, call the method, ... return, return, return, return.
Just try to do it manually as if you were the computer. What would you do in which order, then?
Upvotes: 0
Reputation: 3037
That is the whole point of recursion.
You call *printtest(10)*
, which call *printtest(9)*
before printing sysout...which call printtest(8)
and so on...until printtest(0)
, where it just returns control and now each invocation on stack starts printing its local value of j, which starts from 1,2,3...upto 10.
Concepts to learn: Call stack Java Call Stack
Upvotes: 2
Reputation: 394146
printtest(10)
prints 10 only after the call to printtest(9)
returns, which prints 9 only after the call to printtest(8)
returns, and so on...
The first output is printed when printtest(0)
returns, after which 1 is printed, then printtest(1)
returns and 2 is printed, and so on...
Upvotes: 5