Power of a Number Program in C++

To find the power of a number in C++, use pow() function of cmath library, or use a loop to multiply this number iteratively power number of times.

Power of a Number using pow() Function

In the following program, we will find the power of a number using pow() function of cmath library. pow() function takes the base and exponent as arguments respectively.

C++ Program

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    int base, exponent;
    cout << "Enter base : ";
    cin >> base;
    cout << "Enter exponent (power) : ";
    cin >> exponent;
    
    int result = pow(base, exponent);
    
    cout << "Result : " << result << endl;
}

Output

Enter base : 5
Enter exponent (power) : 3
Result : 125
Program ended with exit code: 0
Enter base : 2
Enter exponent (power) : 3
Result : 8
Program ended with exit code: 0

Power of a Number using While Loop

In the following program, we find base to the power of exponent using C++ While Loop.

C++ Program

#include <iostream>
using namespace std;

int main() {
    int base, exponent;
    cout << "Enter base : ";
    cin >> base;
    cout << "Enter exponent (power) : ";
    cin >> exponent;
    
    int i = 0, result = 1;
    while (i < exponent) {
        result = result * base;
        i++;
    }
    
    cout << "Result : " << result << endl;
}

Output

Enter base : 2
Enter exponent (power) : 3
Result : 8
Program ended with exit code: 0
Enter base : 5
Enter exponent (power) : 2
Result : 25
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned how to find the power of a number in C++, with example programs.