What really does it?
return n + sum( n - 1);
The method sum()
keeps calling itself always passing as parameter the very number that received as argument minus one, until that number reaches zero that will be when it returns zero. That is, if you pass the number 8, it will return 8 plus the return method sum(7)
, which will return 7 plus the return of the method sum(6)
, which will return 6 plus the return of the method sum(5)
, that will return 5 more.... until reaching 0, ie each time you call the method sum()
, it sums this value with all its lower values to zero.
For the case in question the return would be: 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
, that is to say: 36
.
To try to debug, I put some 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;
}
}
}
Upshot:
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 result: 36
Realize there are two prints
within the else
in the method sum()
, but only the first is shown until the end point of the recursion is reached, which is when n
comes to 0
, and instead of calling the method itself again it simply returns a value.
Why should there be
0
?– ramaral
It arrives at 0 yes. The line you are in doubt is the most important, there calling the recursive function. 0 is the stop point, it subtracts the number reported from 1 to 1 until 0.
– George Wurthmann
@Georgewurthmann AP refers to the result of
n + sum( n - 1);
– ramaral