Let's write a definition of the sum()
function in words:
The sum of all natural numbers up to n
is n
plus the sum of the natural numbers up to n-1
.
Notice that this definition is recursive because I need to calculate the sum for a smaller number in order to calculate the sum for a given number. Using this as a guide, we might try something like this:
int sum(int n) {
return n + sum(n - 1);
}
If you try to run this with some test code, you will get a stackoverflow. This is because we have not given a base case to tell when the iteration stops. This base case is implicit in our definition above. The smallest natural number is zero. We are simulating natural numbers with the int
type which stores integers. So we need to modify our code slightly to make sure we do not allow negative integers:
int sum(int n) {
if (n <= 0)
return 0;
return n + sum(n - 1);
}
I think part of the problem you are encountering is that you want to use an accumulator. Often with recursive solutions this is not necessary since the recursive call can immediately return the accumulated value.
Analysis:
Let's take a look at how this works with an example:
void main() {
int x = sum(3);
printf("%d\n", x);
}
Level 1
The first line calls sum()
and sets n
to 3.
int sum(int n) {
if (n <= 0)
n
is not less than or equal to zero, so we skip to the return
return 0;
return n + sum(n - 1)
Now we call sum()
again with a value of n-1
which is 2
}
Level 2
Now sum()
is evaluated with n
set to 2.
int sum(int n) {
if (n <= 0)
Again we skip the if
statement.
return 0;
return n + sum(n - 1);
And sum()
is called with a value of 1.
}
Level 3
int sum(int n) {
if (n <= 0)
Since n
is 1, we skip the if
.
return 0;
return n + sum(n - 1);
Now we call sum(0)
.
}
Level 4
int sum(int n) {
if (n <= 0)
return 0;
Since n
is 0, we return 0. This sends execution back to
Level 3
return n + sum(n - 1);
On this level n
is 1 and Level 4 returned a value of 0. Adding these together and we return a value of 1 back to Level 2.
Level 2
return n + sum(n - 1);
On this level n
is 2 and Level 3 returned a value of 1. Adding these together and we return a value of 3 back to Level 1.
Level 1
return n + sum(n - 1);
On this level n
is 3 and Level 2 returned a value of 3. Adding these together and we return a value of 6 back to main()
.
printf("%d\n", x);
Finally, main()
prints the value of x
which was set to 6.