I am trying to write a recursive function in Java that prints the numbers one through n. (n being the parameter that you send the function.) An iterative solution is pretty straightforward:
public static void printNumbers(int n){
for(int i = 1; i <= n; i++){
System.out.println(i);
i++;
}
As a new programmer, I’m having troubles figuring out how a recursive version of this method would work.
You are using a for loop that is iterating from
i=1ton. As you want to do this with recursion and it is easier to passninstead ofiandn, we just reverse the whole thing, so we count downnto1. To keep the order of the prints, we first call the recursive function and print the number after the execution:For simple iterative -> recursive conversions it is easy to change loops into a format like this:
Now you can easily transform that into a recursive function:
Everything else is optimization.