30.0k views
5 votes
Recursive Power Function Write a function that uses recursion to raise a number to a power. The function should accept two arguments: the number to be raised and the exponent. Assume that the exponent is a nonnegative integer. Demonstrate the function in a program.

User Odyth
by
8.8k points

1 Answer

5 votes

Answer:

// here is code in c++.

#include <bits/stdc++.h>

using namespace std;

// recursive function to calculate power of number

int cal_pow( int b_num, int e_num )

{

if ( e_num > 1 )

return b_num * cal_pow( b_num, e_num - 1 );

else

return b_num;

}

int main()

{

// variables to store inputs

int b_num, e_num;

cout <<"Enter the base (int): ";

//read the base

cin >> b_num;

cout << "Enter the exponent (int): ";

// read the exponent

cin >> e_num;

// call the function and print the output.

cout << b_num << " to the " << e_num << " power is: "

<< cal_pow( b_num, e_num ) << endl;

return 0;

}

//

Step-by-step explanation:

Read value of base and exponent from user. Call the function cal_pow() with parameter base and exponent. In this function, it will call itself and multiply base value while exponent becomes 1.When exponent becomes 1 then base value will be return by the recursive function. In the last recursive call it will give the base to power exponent

Output:

Enter the base (int): 3

Enter the exponent (int): 5

3 to the 5 power is: 243

User Ausgeorge
by
8.7k points