About recursion

I'm trying to write a program accepts a postive integer and calculates

f(x)=1^1+2^2.........+x^x

by using recursion;

i'm a really newbie in c++, plz help~

#include <iostream>
#include <cmath>

using namespace std;


int powerSum (int num,char y)
{
num = y;

if (y==1){

return y;
}


y = powerSum * int pow(y--,y--);
return y;

}

int main(){
int x;
cout<<"Please enter a positive integer:";
cin >> x;
if (x!=0)
cout<<"Invalid Input.";
else
cout<<x<<"after calculation is"<<powerSum (int y)<<endl;

system("PAUSE");
return 0;
}


it appears a few errors

line 17 expected primary-expression before"int"
line 17 expected";" before"int"

line 29 expected primary-expression before"int"





the line 17 error comes from the fact that you are making a function call, not a declaration, so you shouldn't have int before the pow() function.

the line 29 error is that when you call a function you don't need to include the int y part, you just put the variable you want the function to act on (in this case "x" I assume?)

You also have a few other problems:
Right now your if(x!=0) is saying that if x is any number other than zero it will print Invalid Input and quit. I think you want if(x==0) for that condition.

There are other problems as well, but if you fix the first two you should at least be able to compile, then we can work on the others.


edit: btw, if you're smart, you'll rewrite this code to just use the pow function rather than trying to implement it yourself.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
int PowerSum(int n)
{
    if(n == 1)
    {
        return 1;
    }
    else
    {
        return pow(n,n) + PowerSum(n-1);
    }
}
Topic archived. No new replies allowed.