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;
elsereturn x + sum(x - 1);
}
int main() {
cout << sum(4) << endl;
}
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;
elsereturn x + sum(x - 1);
}
Run this code with the gear icon at the top right.