Akhilesh Kumar - 2 months ago 7
Java Question

# Recursion is giving reverse output

I have logic as follows:

I think It should print from 9 - 0
But it is printing from 0 - 9 as follows:

Your output is correct. Lets look at the recursion you are going through.

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

now lets say we start at 10. Going through the method, we would get to the else statement, and call `printArray(9);` Now, we don't go down to the `System.out.println("[" + (i-1) + "]" + values[i-1]);` yet because we are in `printArray(9)` still.

And it goes all the way down to `printArray(0)`, when it returns.

Once it returns, it will go back up the stacktrace to `printArray(1)`, which will get sent to the `System.out.println("[" + (i-1) + "]" + values[i-1]);`, which in turns prints `[0] 0`, returns back up the stacktrace to `printArray(2)`, and prints `[1] 1` and so forth.

You could instead move the `System.out.println` line up to the else statement, and that would give your desired output.

``````void printArray(int i) {
if( i == 0 )
{
return;
}
else
{
System.out.println("[" + (i-1) + "]" + values[i-1]); //Move to here, print starting at the value, then recursively call the next print.
printArray( i - 1 ); //After printing, call the next index to print.
}

}
``````

Another solution is you could instead start at index 0 and go all the way to the length of the array. So instead of passing a parameter you could just call `printArray()` as follows:

``````public void printArray() {
printArray(0);
}

private void printArray( int i ) {
if( i == values.length )
{
return;
}
else
{
printArray( i + 1 );
}
System.out.println("[" + ( i ) + "]" + values[i]);
}
``````

In my opinion, this is the best solution, as then you don't have to necissarily know how big your array is and pass that index into the method. instead, you can just call `printArray()` and that will take care of everything for you.

Source (Stackoverflow)