Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this recursion loop code executes

Tags:

java

recursion

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:

  1. Starts execution from line 3, i.e. invokes printit() with 2 as parameter.
  2. line 6, if condition checks n value if greater than zero, then controls goes to line 7, i.e. prinit() invokes again by decrements n value once.
  3. step 2 continuous execution until n value becomes 0, then line 6, if condition is false. so in line 9, SYSO prints 0.
  4. Then, unable to understood that, how the control again goes from line 10 to 5 ??
like image 669
Gupta Avatar asked Apr 13 '14 04:04

Gupta


1 Answers

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: enter image description here

EDIT 1: Alternatively below image explains: enter image description here

like image 135
Abhishek Nayak Avatar answered Oct 02 '22 07:10

Abhishek Nayak