1. Member Join Date
Apr 2015
Posts
2
Rep Power
0

## recursion question

void printArray(int i)
{
if(i==0) return;

else printArray(i-1);
System.out.println("["+(i-1+"]"+values[i-1]));

}
explain above code for i =1 value  Reply With Quote

2. ## Re: recursion question

Please go through BB Code List - Java Programming Forum - Learn Java Programming and edit your post accordingly. Originally Posted by kanika explain above code for i =1 value
You first. Tell us what you think it does.

db  Reply With Quote

3. Moderator   Join Date
Apr 2009
Posts
13,541
Rep Power
27

## Re: recursion question

What do you think happens?
Have you tried to step through it, say on a piece of paper?

ETA: And just exactly how slow am I?  Reply With Quote

4. Member Join Date
Apr 2015
Posts
2
Rep Power
0

## Re: recursion question Originally Posted by kanika void printArray(int i)
{
if(i==0) return;

else printArray(i-1);
System.out.println("["+(i-1+"]"+values[i-1]));

}
explain above code for i =1 value
the output is 0
but i want to know what happens after where the control go after
else printArray(i-1);
and when i==0
where the control goes

the full program is

public 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]));

}

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

the output is
0
1
2
3
4
5
6
7
8
9  Reply With Quote

5. Moderator   Join Date
Apr 2009
Posts
13,541
Rep Power
27

## Re: recursion question

Darryl posted a link for BBCodes.
You need to use the code tag to format your code, as that lot is hard to read.

And you need to tell us what you think happens, not simply ask the same question.  Reply With Quote

6. ## Re: recursion question

I normally explain recursion with my 'schizophrenic me' example, so here goes: if someone asks me to recursively print out n numbers from an array, I brag that I can do it; I do know that nothing needs to be printed if n == 0 and I can print one number (the last one): array[n-1]. For the rest I ask my clever (but shy) friend to do the job; this is what it looks like:

Java Code:
```void me(int[] array, int n) { // this is me, bragging
if (n > 0) {
friend(array, n-1); // he does the  hard work
System.out.println(array[n-1]); // I do the last number
}
}```
But sadly enough I don't have a friend; it's purely my imagination; my friend is me, so:

Java Code:
```void me(int[] array, int n) { // this is me, bragging
if (n > 0) {
me(array, n-1); // he^H^HI does^H^H the  hard work
System.out.println(array[n-1]); // I do the last number
}
}```
kind regards,

Jos  Reply With Quote

code, method, recursion 