What really does this?
return n + sum( n - 1);
The sum()
method is always invoked by passing as a parameter the number itself received as an argument minus one, until that number reaches zero which will be when it returns zero. That is, if you pass the number 8, it will return 8 plus the return of the sum(7)
method, which will return 7 plus the return of the sum(6)
method, which will return 6 plus the return of the sum(5)
method, which will return 5 more .... until it reaches 0, that is, every time you call the sum()
method, it adds that value with all its lower values until it reaches zero.
For the case in question the return would be: 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
, that is: 36
.
To try to debug, I put prints
to show what happens in each iteration:
public class Recursivo{
public static void main(String[] args) {
int result = sum(8);
System.out.println("Resultado final: " + result);
}
public static int sum(int n){
if( n == 0){
System.out.println("Fim da recursividade");
return 0;
}
else
{
System.out.println("O valor de n nessa iteração é: " + n);
int ret = n + sum( n - 1);
System.out.println("O valor a ser retornado nessa iteração é: " + ret);
return ret;
}
}
}
Result:
The value of n in this iteration is: 8
The value of n in this iteration is: 7
The value of n in this iteration is: 6
The value of n in this iteration is: 5
The value of n in this iteration is: 4
The value of n in this iteration is: 3
The value of n in this iteration is: 2
The value of n in this iteration is: 1
End of recursion
The value to be returned in this iteration is: 1
The value to be returned in this iteration is: 3
The value to be returned in this iteration is: 6
The value to be returned in this iteration is: 10
The value to be returned in this iteration is: 15
The value to be returned in this iteration is: 21
The value to be returned in this iteration is: 28
The value to be returned in this iteration is: 36
Final score: 36
Notice that there are two prints
within else
in method sum()
, but only the first one is shown until the end point of the recursion is reached, which is when n
reaches 0
, and instead of calling the method itself it simply returns a value.