Recursion example

Hello,

I know the returned value will be 9 in this code, but how? I've been staring at this for like an hour while trying to do the math on paper but I can't seem to figure it out.

1
2
3
4
5
6
7
  int sum(int x) {
      if(x == 2) return x;
      else return x + sum(x - 1);
}      
  int main() {
      cout << sum(4) << endl; 
}  
4 + 3 + 2 = 9
How did you get those numbers? Sorry I don't quite understand.
Hi,

It's doing this:

sum(4) + sum(3) + sum(2)

sum(2) is the base case (the end condition on line 2), and returns 2

so we have:

4 +3 +2 = 9

Good Luck !!
Hi again,

Thought of something else which may help visualise:

Put a std::cout statement that prints the value of x, after line 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int sum(int x);

int main() {
      std::cout << sum(4) << "\n"; 
}  


  int sum(int x) {
       std::cout << "The value of x is " << x << "\n";
      if(x == 2) return x;
      else return x + sum(x - 1);
}      


Run this code with the gear icon at the top right.
This is perfect!! Thanks a ton!
Topic archived. No new replies allowed.