You are using a for loop that is iterating from i=1
to n
. As you want to do this with recursion and it is easier to pass n
instead of i
and n
, we just reverse the whole thing, so we count down n
to 1
. To keep the order of the prints, we first call the recursive function and print the number after the execution:
public static void printNumbers ( int n )
{
if ( n > 0 )
{
printNumbers( n - 1 ); // n - 2, if the "i++" within the for loop is intended
System.out.println( n );
}
}
For simple iterative -> recursive conversions it is easy to change loops into a format like this:
public static void printNumbers ( int n )
{
int i = 1;
while ( i <= n )
{
System.out.println( i );
i++; // i += 2, if the "i++" within the for loop is intended
}
}
Now you can easily transform that into a recursive function:
public static void printNumbers ( int n, int i )
{
if ( i <= n )
{
System.out.println( i );
i++; // i += 2, if the "i++" within the for loop is intended
printNumbers( n, i );
}
}
Everything else is optimization.