I have some line of code where i cannot understand how the codes are executes, i mean the flow of program.
Code:
1) public class RecurLoopTest {
2) public static void main(String[] args) {
3) printit(2);
4) }
5) private static int printit(int n){
6) if(n>0){
7) printit(--n);
8) }
9) System.out.print(n+",");
10) return n;
11) }
12) }
I am thinking output should be: 0,
But Output is: 0,0,1,
I have done DEBUG above class so many time, The flow i have seen while debugging:
- Starts execution from line 3, i.e. invokes printit() with 2 as parameter.
- line 6, if condition checks
nvalue if greater than zero, then controls goes to line 7, i.e. prinit() invokes again by decrements n value once. - step 2 continuous execution until n value becomes 0, then line 6, if condition is false. so in line 9, SYSO prints 0.
- Then, unable to understood that, how the control again goes from line 10 to 5 ??






printit()in line 7 is finished, the rest of the function executes. Each invocation ofprintit()prints output after the recursive call is complete, so it essentially does three print-outs "on the way out" of the recursion. This is why the output is a set of three values, not just a single value like you said you were expecting.