# How to use “pow” function in C++

In this context, we will learn how to use pow function in C++ to find the power of a given number to another given number.

The function pow is a predefined function of the “Math” library. To invoke the “Math” library we have to introduce the “<math.h>” header file. Without using the math function we still can determine the power of a number by using the loop and multiplying the number with itself the required number of times.

**Illustration of the above concept:**

Example 1: Insert a base: 4 Insert an exponent :2 The result is 16 Example 2: Insert a base: 2 Insert an exponent :0 The result is 1

Also, read: Mathematical functions in C++

## Power of a number in C++ without using pow function in C++

We can also write this same program without using the “pow” function. The program would look something like this:

#include<iostream> using namespace std; int main() { int b,p,res=1,i; cout<<"Insert the base:"; cin>>b; cout<<"Insert the power:"; cin>>p; for(i=0;i<p;i++) res=res*b; cout<<"The result is :"<<res; return 0; }

The program will continuously multiply the base with itself the number of times the power is given. The alternative to this program would be using the pow function which is demonstrated below.

#### Algorithm of the program:

- Insert the value of exponent and base and store them in different variables(ex and base respectively).
- Invoke the pow function by calling res=pow(base, ex) and store the result in res.
- Print the result.

## Example of pow() function in C++

#include<iostream> #include<cmath> using namespace std; int main() { int ex,b,res; cout<<"Input the base :"; cin>>b; cout<<"Input the exponent :"; cin>>ex; res=pow(b,ex); cout<<b<<"^"<<ex<<"="<<res; return 0; }

#### The output of the above problem :

This is a very simple program. I tried my best to do it in the easiest way possible. Hope you like it. If you have any doubts, please comment below.

## Leave a Reply

You must be logged in to post a comment.