Write a power (pow) function using C++

C++ProgrammingServer Side Programming

The power function is used to find the power given two numbers that are the base and exponent. The result is the base raised to the power of the exponent.

An example that demonstrates this is as follows −

Base = 2
Exponent = 5

2^5 = 32

Hence, 2 raised to the power 5 is 32.

A program that demonstrates the power function in C++ is given as follows −

Example

 Live Demo

#include
using namespace std;

int main(){
   int x, y, ans = 1;

   cout << "Enter the base value: \n";
   cin >> x;

   cout << "Enter the exponent value: \n";
   cin >> y;

   for(int i=0; i<y; i++)
   ans *= x;

   cout << x <<" raised to the power "<< y <<" is "<&;lt;ans;

   return 0;
}

Example

The output of the above program is as follows −

Enter the base value: 3
Enter the exponent value: 4
3 raised to the power 4 is 81

Now let us understand the above program.

The values of base and exponent are obtained from the user. The code snippet that shows this is as follows −

cout << "Enter the base value: \n";
cin >> x;

cout << "Enter the exponent value: \n";
cin >> y;

The power is calculated using the for loop that runs till the value of the exponent. In each pass, the base value is multiplied with ans. After the completion of the for loop, the final value of power is stored in the variable ans. The code snippet that shows this is as follows −

for(int i=0; i<y; i++)
ans *= x;

Finally, the value of the power is displayed. The code snippet that shows this is as follows −

cout << x <<" raised to the power "<< y <<" is "<<ans;
raja
Published on 06-Nov-2018 09:33:30
Advertisements