Answer the question
In order to leave comments, you need to log in
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);
}
}
По моей логике:
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 и на выход
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question