So I am working on learning how to utilize recursion through Java. I have written a simple program that adds all the numbers between 1 and n and it looks to do it\'s job. Wh
Let me explain why this happens.
Your second print statement prints all the sum values except for when n
= 1. When n
= 1 the first print statement will print out the value
Think about this this way: Every non-void method call will return. If it does not return, it will continue executing until a return statement is reached.
You say that the second print statement should print only the last sum value. But you see, there are only two places that the method can return - in the if (num == 1)
statement, or at the end of the method. The former location is reached only once when n is 1, which means that the other four times the method will return through the return statement at the end. To reach the return statement at the end, the second print must be executed. This means that the second print statement must be executed four times!
Use a debugger to step through the code step by step. This is the easiest to understand what actually happens.