###### C++ Decision Making

C++ Program to Calculate Power of a Number.

# C++ Program to Calculate Power of a Number

In this example, we will learn to compute power to a number manually, and by using pow() function.

To understand this example, you should have the knowledge of the following C++ programming topics:

## Power of a Number

This program takes two numbers from the user (a base number and an exponent) and calculates the power.

Power of a number = baseexponent

## Example 1: Program to Compute Power Manually

#include <iostream>
using namespace std;

int main()
{
int exponent;
float base, result = 1;

cout << "Enter base and exponent respectively:  ";
cin >> base >> exponent;

cout << base << "^" << exponent << " = ";

while (exponent != 0) {
result *= base;
--exponent;
}

cout << result;

return 0;
}

Output

Enter base and exponent respectively:  3.4
5
3.4^5 = 454.354
##### Working

As we know, the power of a number is the number multiplied by itself repeatedly. For example,

53 = 5 x 5 x 5 = 125

Here, 5 is the base and 3 is the exponent.

In this program, we have calculated the power of a number using a while loop.

while (exponent != 0) {
result *= base;
--exponent;
}

Remember that we have already initialized result as 1 during the beginning of the program.

Let us see how this while loop works if base == 5 and exponent == 3.

Iteration result *= base exponent exponent != 0 Execute Loop?
1st 5 3 true Yes
2nd 25 2 true Yes
3rd 125 1 true Yes
4th 625 0 false No

However, the above technique works only if the exponent is a positive integer.

If you need to find the power of a number with any real number as an exponent, you can use pow() function.

## Example 2: Program to Compute power using pow() Function

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
float base, exponent, result;

cout << "Enter base and exponent respectively:  ";
cin >> base >> exponent;

result = pow(base, exponent);

cout << base << "^" << exponent << " = " << result;

return 0;
}

Output

Enter base and exponent respectively:  2.3
4.5
2.3^4.5 = 42.44
##### Working

In this program, we have used the pow() function to calculate the power of a number.

Notice that we have included the cmath header file in order to use the pow() function.

We take the base and exponent from the user.

We then use the pow() function to calculate the power. The first argument is the base, and the second argument is the exponent.

## Next Example

We hope that this Example helped you develop better understanding of the concept of "Find Power of a Number" in C++.

Keep Learning : )

In the next Example, we will learn about C++ Program to Check a Number is Palindrome or Not.