Recursion calculation doesn't work.

My current output doesn't show the calculations and it counts f(n) down from what the user inputs to f(0). How do I get it to count up starting with the base case f(0) to f(n) and also calculate this recursive case formula f(n) = 2 * f(n-1) -3? This is just twisting my brain for some reason, any help greatly appreciated.

An example output that I'm supposed to get with my base case f(0)=5, is: f(0): 5, f(1): 7, f(2): 11, f(3): 19, f(4): 35, f(5): 67, f(6): 131, f(7): 259, f(8): 515

#include <iostream>

using namespace std;

int f(int n);

int main (){
int number;

cout << "Enter a number greater than or equal to 0: ";
cin >> number;

while(number<0){
cout << "Please enter a valid number!" << endl;
cout << "Enter a number greater than or equal to 0: ";
cin >> number;
}

f(number);
}

int f(int n){

//Base Case
if (n==0){
cout << "f(" << n << "): " << 5 << endl;
}

//Recursive case
else{
cout << "f(" << n << "): " << endl;
2 * f(n-1)-3;
}
}
f should return a value?

I would think
if zero
{
stuff;
return 5
}
else
{
otherstuff;
return 2*f(n-1)-3;
}




1
2
3
4
5
6
int f(int n) {
    cout << "f(" << n << ")\n";
    if (n <= 0)
        return 5;
    return 2 * f(n - 1)  - 3;
}

Thanks guys! It works now.
Topic archived. No new replies allowed.