-4
void printarray(int i) {
    if (i == 0) {
        return;
    } else {
        printarray(i - 1);
    }
    System.out.println("[" + (i - 1) + "]" + values[i - 1]);
}

Its a program that prints the array using recursion. Can anybody tell me how does the above method works??

Turing85
  • 18,217
  • 7
  • 33
  • 58
arunoday singh
  • 222
  • 2
  • 13

2 Answers2

1

The method prints an array that has to be an instance or class variable with the name values.

The initial given index is not taken into account.

The method starts at the topmost index and calls itself with an index decremented by one. When it reaches index 0, this is the start of the return-chain. After returning from the recursion call, the value at the current index is printed - after the index itself.

One call is printed under the next. The lines start at index 0 and stop at index i - 1 (the index used for the initial call).

Update: thanks to @Turing85 I fixed my own assumption of the printed indexes.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
  • 2
    @Turing85 i want to know 1 thing.if i==0 it returns then in the last line the value of i beomes 1.am i right??? – arunoday singh May 23 '17 at 18:25
  • @arunodaysingh I am not able to follow your thought. A method is immediately aborted, if a `return` is reached. From this point, execution continues one call stack above, (most likely `printarray`). This call frame has its own (old) value of `i` since Java is pass-by-value always. – Turing85 May 23 '17 at 18:28
  • 2
    @Turing85 thanks a lot for your help. actually i forgot the call by value.i wasnot able to understand how the last line started with i=1.but with your comments i am able to understand.thanks a lot for your help.. – arunoday singh May 23 '17 at 18:39
0

Example: i = 3 => printarray(3)

  • else block is active: printarray(2)
  • else block is active: printarray(1)
  • else block is active: printarray(0)
  • if block is active, because i = 0 and return
Patzi0207
  • 13
  • 7