C++ for Beginners: C++ Program to Calculate Power Using Recursion

Hits: 22

(C++ programming Example for Beginners)

C++ Program to Calculate Power Using Recursion

This program calculates the power of a number using recursion where base and exponent is entered by the user.


Example: Program to Computer Power Using Recursion


#include <iostream>
using namespace std;

int calculatePower(int, int);

int main(){
    int base, powerRaised, result;

    cout << "Enter base number: ";
    cin >> base;

    cout << "Enter power number(positive integer): ";
    cin >> powerRaised;

    result = calculatePower(base, powerRaised);
    cout << base << "^" << powerRaised << " = " << result;

    return 0;
}

int calculatePower(int base, int powerRaised){
    if (powerRaised != 0)
        return (base*calculatePower(base, powerRaised-1));
    else
        return 1;
}

Output

Enter base number: 3
Enter power number(positive integer): 4
3^4 = 81

This technique can only calculate power if the exponent is a positive integer.

To find power of any number, you can use pow() function.

result = pow(base, exponent);

 

C++ for Beginners: C++ Program to Calculate Power Using Recursion

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.