fastread homefastrread library fastread menu

C++ : Calculate Power of a Number

Tutorial by:Manisha Dubey      Date: 2016-06-18 04:19:43

❰ Previous Next ❱

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

Power of a number = baseexponent

This program below assumes that the user always enters a non-negative integer as exponent.

Source Code to Calculate Power of a Number

#include <iostream>
using namespace std;

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

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

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

    cout << "Result = " << power;
    
    return 0;
}

 

 
 

Output

Enter base and exponent respectively:  3.4
3
Result = 39.304

To calculate power of a number with any exponent, you can use pow() function which is a standard library function. You have to include header file to use pow() function.

Source Code to Calculate Power with pow() Function

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

int main() {
    int exp;
    float base;

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

    cout << "Result = " << pow(base, exp);
    return 0;
}

The output of this program is same as above program

❰ Previous Next ❱


C++

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website