Explanation
The method sums up all values up to the given argument. The argument is 3
, the result is thus 6 = 3 + 2 + 1
.
Therefore, the method uses recursion. That is, the method calls itself. It exploits the property that
sum(n) = n + sum(n - 1)
for any integer n.
Iterative
Let's first take a look at an equivalent method that don't uses recursion:
public static int sum(int number) {
int result = 0;
for (int i = number; i >= 1; i--) {
result += i;
}
return result;
}
Called with 3
the method has three iterations. It adds 3
to result
, then 2
and finally 1
, resulting in 6
.
Recursive
Your recursive method does a similar thing. It takes 3
and adds the result of sum(2) = 2 + 1
to it. sum(2)
is computed with the same technique, it takes 2
and adds sum(1) = 1
to it. sum(1)
itself does not trigger another computation since it does not call sum
again, take a look at your code:
if (number == 1)
return number;
Again, let's take a look at the code:
return number + sum(number - 1);
So calling with 3
yields 3 + sum(3 - 1)
, which is 3 + sum(2)
. In order to compute this, the method sum
must be called again, with the argument 2
. Calling with 2
yields 2 + sum(1)
. In order to compute this, the method is called with 1
. The call returns 1
.
Substituting everything back yields:
sum(3) = 3 + sum(2)
= 3 + (2 + sum(1))
= 3 + (2 + (1))
= 6