Recursive function

How do I write a recursive function to compute (3^2)+(3^3)+(3^4).......+(3^n) ?
Look at the pattern backwards: (3^n)+...(3^4)+(3^3)+(3^2)

Make a function that returns an int, and has a int parameter.

if "i" is greater than 2:
return 3^i + the_function(i-1);,
else if its equal to 2:
return 3^2;,
otherwise:
else{ std::cout<<"error: input must be equal or greater than 2.\n"; return 0;}
cmath provides pow to make the 3^n part

1
2
3
4
5
6
int name_of_the_function(int base, int power)
{
    if(power == 2)
        return pow(base, power);
    return pow(base, power) + function(base, power - 1);
}
Topic archived. No new replies allowed.