In this C++ tutorial, you will learn how to write a program to compute the power of a number (base raised to the power) using cmath::pow() function, or a While loop.

C++ Power of a Number

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.

1. Find 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
ADVERTISEMENT

2. Find 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.