``````#include <iostream>
using namespace std;
int f(int i) {
if(i == 1) {
return (1);
}
else {
return 2*f(i-1);
}
}

int main() {
cout << f(5) << endl; //<--- I don't understand why this is 16.
return 0;

}
``````

I am having trouble understanding why f(5) = 16 when I run the program.
i = 5 // 2(4) = 8
i = 4 // 2(3) = 6
i = 3 // 2(2) = 4
i = 2 // 1
these don't add to 16. I would really appreciate some guidance.

2
Contributors
2
Replies
20
Views
4 Years
Discussion Span
Last Post by kruschev

We call the function f(5).

What does f(5) return? It returns 2 * f(4).
What does f(4) return? It returns 2 * f(3), so let's put that back into "what does f(5) return?"

What does f(5) return? It returns 2 * f(4) = 2 * 2 * f(3)

So what does f(3) return? It returns 2 * f(2), so let's put that back into "what does f(5) return?"

What does f(5) return? It returns 2 * f(4) = 2 * 2 * f(3) = 2 * 2 * 2 * f(2)

So what does f(2) return? It returns 2 * f(1), so let's put that back into "what does f(5) return?"

What does f(5) return? It returns 2 * f(4) = 2 * 2 * f(3) = 2 * 2 * 2 * f(2) = 2 * 2 * 2 * 2 * f(1)

So what does f(1) return? It returns 1, so let's put that back into "what does f(5) return?"

What does f(5) return? It returns 2 * f(4) = 2 * 2 * f(3) = 2 * 2 * 2 * f(2) = 2 * 2 * 2 * 2 * f(1) = 2 * 2 * 2 * 2 * 1

So what does f(5) return? 2 * 2 * 2 * 2 * 1 = 16

Thank you very much! It is very clear now.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.