446,171 Members | 1,004 Online Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

# power using recursion

 P: 17 the question is to calculate x^n(x power n) (whr n can be +ve or -ve) by using recursion. the algorithm is x= 1, n=0 1/x^n, n<0 x*x^(n-1), n>0 ive written the program it runs but im not having the correct values..here is the code: Expand|Select|Wrap|Line Numbers #include #include   int power(int n); int x,n; void main() {clrscr(); cout<<"Input a value for x"<>x; cout<<"\n Input a value for n"<>n; cout<<"The final answer is"<
3 Replies

 Expert 100+ P: 1,510 should you equation for x^n be Expand|Select|Wrap|Line Numbers       return (x*power(n-1));   Feb 17 '07 #2

 Expert 2.5K+ P: 3,652 the algorithm is x= 1, n=0 1/x^n, n<0 x*x^(n-1), n>0 Expand|Select|Wrap|Line Numbers int power(int n) {    if (n==0)       return 1;   else if (n<0)       return (1/(x*power(n)));   else       return (x*(x*power(n-1))); } The problem appears to be in your second branch. If n < 0, you will indeed call the recursive function again, but you are passing it the same value of n. This value is negative still, and so you will always execute the second branch. Thus, n never changes, and your end condition is never reached. While you coded your given algorithm correctly, the algorithm itself is wrong. Try this algorithm: x^n = 1 / (x ^ |n|), where n < 0 and |n| is the absolute value of n. Also, your third branch (for n > 0) multiplies the value by an extra x. It should just be x * power(n-1). Next I'd suggest passing power the x value as well, rather than having both values declared as global. This will make the function portable, so you will not have to rewrite a recursive power function ever time you need one. Finally, 1 / anything will be a double value, but your function returns an integer. This means that any negative exponent created will be returned as x. You should make this function return a double. Feb 17 '07 #3

 Expert 100+ P: 1,251 Expand|Select|Wrap|Line Numbers int power(int n) { if (n==0)       return 1;   else if (n<0)       return (1/(x*power(n)));   else       return (x*(x*power(n-1))); } Ganon11 forgot to mention that your second branch should be returning x*(1/power(n+1)). Adrian P.S. As Ganon11 stated, You really shouldn't be using global variables Get power to take a param double x. And move the n inside of the main(). Using global variables is a very bad form to get used to and it will bite you in the ass later. Feb 17 '07 #4 