A
A
Andrey Kulagin2020-02-14 22:00:20
Java
Andrey Kulagin, 2020-02-14 22:00:20

How does recursion work on an array?

There is a code:

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);
    }
}


And the result
is the result of the work [0]0
[1]1
[2]2
[3]3
[4]4
[5]5
[6]6
[7]7
[8]8
[9]9

По моей логике:
1.   for(i=0;i<10;i++) ob.values[i]=i; // заполняются элементы массива от 0 до 9 соответственно
2.  Затем отрабатывает ob.printArray(10);
Где 
 if(i==0) return;
 else printArray(i-1);    отрабатывает от 10 до 0 и на выход

in the end System.out.println shouldn't be used at all and it outputs how it works?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-02-14
@andrew_1985

It works like this:
When i becomes equal to 0, it executes return.
This return returns to the place where the printArray method was called from (remember that it was called recursively).
The next line after the call to printArray is System.out.println("["+(i-1)+"]"+values[i-1]);, which is executed the corresponding number of times for the corresponding i

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question