167k views
2 votes
Write a function named power that accepts two parameters containing integer values (x and n, in that order) and recursively calculates and returns the value of x to the nth power.

1 Answer

6 votes

Answer:

Following are the code to the given question:

int power(int x, int n)//defining a method power that accepts two integer parameters

{

if (n == 0)//defining if block to check n equal to 0

{

return 1; //return value 1

}

else//defining else block

{

x = x * power(x, --n); //use x variable to call method recursively

}

return x; //return x value

}

Step-by-step explanation:

In the above-given code, a method power is defined that accepts two integer variable in its parameter, in the method a conditional statement is used which can be defined as follows:

  • In the if block, it checks "n" value, which is equal to 0. if the condition is true it will return value 1.
  • In the else block, an integer variable x is defined that calls the method recursively and return x value.
User Massagran
by
4.2k points