C++ Program to calculate the power of a number


January 16, 2023, Learn eTutorial
1087

Here we are explaining how to write a C++ program to find the power of a number.

How can we calculate the power of a number?

The power of a number is the product of multiplying a number by itself. Power is represented with a base number and an exponent. The base number indicates the number being multiplied. An exponent is a small number written above and to the right of the base number, which tells how many times the base number is being multiplied. 

For example:
23,   2 is the base number, and 3 is that number's exponent.
23 = 2 * 2 * 2 = 8
53 = 5 *5 * 5 = 125.

How to implement a C++ program to calculate the power of a number.

Start the program with the main function. Declare an integer type variable to load the exponent value. ‘exp’;  float type variable to load the value of the base. ‘base_value’. And power to hold the result. Initially set the value of power = 1.

A float is a floating-point number, which means a number that has a decimal place. Take two numbers from the user a base number and an exponent.
The calculation can be performed within a while loop.

In the while loop, the condition is evaluated repeatedly and the code inside the loop will execute until the condition goes wrong. Whenever the condition is false, the loop terminates.Here are condition is ( exp != 0 ). Until this condition is satisfied power = power * base_value; after that the value of exp will be decremented by 1. Repeating the process until exp =0; the power of the number will be in the variable power.

Exit the program.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare variables; basepow = 1 as float, and variable exp as integer.

Step 5: Ask the user to enter the base and exponent values.

Step 6: Read the base value to the variable base_value and the exponent value to the variable exp.

Step 7: Calculate the result by using the method power = power * base_value. Until the value of exp =0.

Step 8: decrement the value of the exponent by 1 for each iteration.

Step 9: Display the result

Step 10: Exit.

C++ Source Code

                                          #include <iostream>
using namespace std;

int main() 
{
    int exp;
    float base, pow  = 1;

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

    cout << base << "^" << exp << " = ";

    while (exp != 0) {
        pow  *=  base ;
        --exp;
    }

    cout << pow ;
    
    return 0;
}
                                      

OUTPUT

Run 1
Enter base and exponent respectively:  5
2
5^2 = 25
Run 2
Enter base and exponent respectively:  2.3
3
2.3^3 = 12.167