#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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.