Answer to Question #5076 in C++ for Ghiwa

Question #5076
5. Write a recursive function, power, that takes as parameters two integers x and y such that x is nonzero and returns xy. You can use the following recursive definition:
If y ≥ 0, power(x,y) = 1 if y=0
power(x,y) = x if y=1
power(x,y) = x * power(x, y-1) if y>1
If y <0, power(x,y) = 1/power(x, -y)
Write a program to test your function
1
Expert's answer
2011-11-10T09:55:18-0500
#include <iostream>
using namespace std;

float power(int,
int);

int main() {
int x = 0, y = 0;
cout << "x = ";
cin
>> x;
cout << "y = ";
cin >> y;
cout << x
<< "^" << y << " = " << power(x, y) <<
endl;
return 0;
}

float power(int x, int y) {
if (y ==
0)
return 1;
else if (y == 1)
return x;
else if (y > 1)
return
(x * power(x, y - 1));
else if (y < 0)
return (1 / power(x,
-y));
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS