C++ program to the Power of a number

Program to find the Power of a number

To calculate the power of a number we need the two inputs – base and exponent. These two inputs are passed into a function, pow(input1,input2), as parameters and it will return the result . The function is present in the math.h header file.

For Example: Base – 5 ,  Exponent – 3

pow(Base, Exponent) = pow(5, 3)= 125

Power of Number

Algorithm:-

  1. Take  two inputs from user
  2. Inputs are stored in two double type variable say base & exp.
  3. A function, pow(base, exp) is called with base and exp as parameters.
  4. The calculated power is stored in another variable say res.
  5. res is printed with precision set up to 2 decimal places.
Power of Number

C++ Code:-

 //C++ Program
    //Power of a number
    #include <iomanip>
    #include <iostream>
    #include <math.h>
    using namespace std;
    //main program
    int main() 
    {
        double exp, base;
        cout<<"Enter base: ";
        //user input 1
        cin>>base;
        cout<<"Enter Exponent: ";
        //user input 2
        cin>>exp;
        //calculating power using function
        double res = pow(base, exp);
        //printing result
        cout << base << "^" << exp << " = " ;
        cout << fixed <<setprecision(2)<<res<<endl;
        return 0;
    }

Output

Enter base: 2
Enter Exponent: 2
2^2 = 4.00