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:
n
value if greater than zero, then controls goes to line 7, i.e. prinit() invokes again by decrements n value once.In this program printit()
invoked three times.
how the control again goes from line 10 to 5 ??
Here is how the control flows:
printit(0)
-- n=0
, prints "0,"
, returns 0
printit(1)
-- n=1
, prints "0,"
, returns 0
printit(2)
-- n=2
, prints "1,"
, returns 1
main()
So Output is: 0,0,1,
To understand better put a breakpoint in return statement while debuging.
Here is control/memory flow diagram:
EDIT 1: Alternatively below image explains:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With