C++ for Beginners: C++ Program to Calculate Power of a Number

Hits: 12

(C++ programming Example for Beginners)

C++ Program to Calculate Power of a Number

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


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: 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

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: 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

 

 

C++ for Beginners: C++ Program to Calculate Power of a Number

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.