Home > Mobile >  Can't figure out this recursion program
Can't figure out this recursion program

Time:03-21

I can't seem to figure out why this recursion program prints the values the way it does. I thought it would print [9]9 first but intead it does it backwards from [0]0. Can anyone explain why this happens?

class RecTest {
    int values[];
    
    RecTest (int i){
        values = new int[i];
    }
    
    void printArray(int i) {
        if(i==0) return;
        else printArray(i-1);
        System.out.println("["   (i-1)   "]"   values[i-1]);
    }
}
public class Recursion2 {

    public static void main(String[] args) {
        RecTest ob = new RecTest (10);
        int i;
        
        for(i=0; i<10; i  ) ob.values[i] = i;
        
        ob.printArray(10);
        
    }
}

CodePudding user response:

The printArray method works by calling itself decreasing the integer i. The System.out.println statement is executed after calling the function with i-1. For example, given an input of 10:

  1. printArray(10) is exectued -> printArray(10-1) is called
  2. printArray(9) is executed -> printArray(9-1) is called
  3. [...]
  4. printArray(0) is executed -> return. The program goes back to the previous istance of printArray, the one where i = 1
  5. We are here in the code: the line printArray(1-1) has just been executed. The next line is System.out.println("[" (1-1) "]" values[1-1]) -> [0]0 is printed (right now i = 1). Now the program goes back to the previous instance where i = 2
  6. [...]

I think you can figure out the rest :)

CodePudding user response:

See if this helps.

static void printVal(int i) {
    if (i > 0) {
        System.out.printf("Calling printVal(%d) again%n", i-1);
        printVal(i-1);
    }
    System.out.println("Returning from print - call stack has "   i);
}

printVal(10);

prints

Calling printVal(9) again
Calling printVal(8) again
Calling printVal(7) again
Calling printVal(6) again
Calling printVal(5) again
Calling printVal(4) again
Calling printVal(3) again
Calling printVal(2) again
Calling printVal(1) again
Calling printVal(0) again
Returning from print - call stack has 0
Returning from print - call stack has 1
Returning from print - call stack has 2
Returning from print - call stack has 3
Returning from print - call stack has 4
Returning from print - call stack has 5
Returning from print - call stack has 6
Returning from print - call stack has 7
Returning from print - call stack has 8
Returning from print - call stack has 9
Returning from print - call stack has 10

Each subsequent call to printVal puts the value-1 on the call stack. When they are all finally returned, they return in the reverse order.

  • Related