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

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

Expert's answer

#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));

}

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));

}

## Comments

## Leave a comment