if n equals zero, it returns zero (in effect), otherwise it returns n + calling itself with n - 1. The total effect is that sumToN is called repeatedly until n equals zero. Then it returns zero, then it returns zero + 1, then it returns 1 + 2, then it returns 3 + 3.... until n calls have been reached.
int n = sumToN(5);
// here's what happens:
sumToN(n = 5)
{
is 5 == 0 ? no
return 5 + sumToN(4);
{
is 4 == 0? no
return 4 + sumToN(3);
{
is 3 == 0? no
return 3 + sumToN(2);
{
is 2 == 0? nope
return 2 + sumToN(1);
{
is 1 == 0? no
return 1 + sumToN(0);
{
is 0 == 0? yes
return 0;
// When n == 0, this is the first actual return
// We go back to the call when n == 1
return 1 + 0;
// Now back to the call where n == 2
return 2 + 1;
//Now back to n == 3
return 3 + 3;
//...
return 4 + 6;
return 5 + 10
// Back in main
cout << x; // x is 15.
Recursion can make coding easier, but anything that can be done with recursion can be done with a loop. I would imagine that sumToN is just an example to explain recursion, but here it is as just a loop:
1 2 3 4 5 6 7 8 9 10
sumToN(int n)
{
int x = 0;
while (n > 0) // while (n)
{
x += n;
n--;
}
return x;
}
It has a major weakness to negative numbers, but so does the original.
Edit: A recursive sumToN can be very short:
1 2 3 4
sumToN(int n)
{
return n ? n + sumToN(n - 1) : 0;
}
I think that the function is incorrect. At least it is possible that the author of the function did not want to calculate
-1 + -2 +...+ INT_MIN
Also the function can be simplified:
1 2 3 4
unsignedint sumToN( unsignedint n )
{
return ( ( n == 0 ) ? 0 : n + sumToN( n - 1 ) );
}
And my advice do not use such style of placing braces as in your code
Lol why do you figure that the bracket shouldn't be on the same line as the function call? Or atleast with main? C++ allows it, and there is no standard that it MUST follow...is there???
I came from a JAVA background and that was how I was originally taught. I don't like brackets on their own line, it seems like a waste to me. Why have 200 lines of code when you can have 180 or less?
Also, with proper indentation, I found my code is easily read. I can also use those lines I saved to make the code overall easier to read, seperate cout/cin from conditional statements, use a new line near return, etc.
How about this, aside from just saying my way is wrong, why not show how the different ways are wrong? I'd like to see how unclear and unreadable my code is compared to your style.