Compute Exponent of a Number in C++

Exercise:

Write a C++ program to calculate the power of a number, manually or by pow() function.

Method 1: Determining power manually:

Click Here to View the Solution:
#include <iostream>
using namespace std;
int main() 
{
    int power;
    float num, ans = 1;
    cout <<"Enter the base number:  ";
    cin >> num;
    cout <<"Enter the power of the base number:  ";
    cin >> power;
    cout << num << "^" << power << " = ";
    while (power != 0) 
    {
        ans *= num;
        --power;
    }
    cout << ans;
    return 0;
}
Click Here to View the Output:
Enter the base number:  3
Enter the power of the base number:  5
3^5 = 243
Click Here to View the Explanation:
  • Power of a number is the number of times the number is repeatedly multiplied to the same number. For instance, 3^5 = 243.
  • For this, the power of the number 5 is the exponent and 3 is the base number.
  • While loop is used to compute the exponent. If the power is not equal to zero, the while loop is entered. ans is already assigned equal to 1. And multiplied by itself.
  • ans is multiplied by the base number num through every iteration. power is decremented by 1 through every iteration. And the loop goes on until power is reduced to 0.
  • This code can only work if the entered integer is positive.
  • The power can be calculated using the function pow().

Method 2: Determining the power of a number using pow() function:

Click Here to View the Solution:
#include <iostream>
#include <cmath>
using namespace std;
int main() 
{
    float num, power, ans;
    cout << "Enter a number and its power:\n";
    cin >> num >> power;
    ans = pow(num, power);
    cout << num << "^" << power << " = " << ans;
    return 0;
}
Click Here to View the Output:
Enter a number and its power:
 3
 9
 3^9 = 19683
Click Here to View the Explanation:
  • This is an easier way to compute the power simply using the function pow().
  • The user is requested to enter two numbers, the base num and exponent power.
  • pow() simply calculated the power of the number and it is printed on the screen.

%d bloggers like this: