**C++ raise to power: **In the previous article, we have discussed about C++ Program to Check Leap Year. Let us learn how to Calculate Power of a Number in C++ Program.

## Method to calculate the power of a number in c++

**C++ power of a number: **In this article, we see different methods to calculate the power of numbers in c++. Here we take “a” as our number and “b” as the power. So here we see how can we find a raised to the power p or simply say a^b. Let see the different method to calculate the power of number.

### Method 1-Using loop

**How to raise something to a power in c++: **In this method, we will see how we can calculate the power of a number by iterating through the loop. suppose we have to calculate 2 raised to the power 3 so we can run for loop 3 times and multiply number 3 times in itself and store it in a variable. For better understanding let write code for the program.

#include <iostream> using namespace std; int main() { int a=2,b=3,res=1,i; for(i=0;i<b;i++) { res=res*a; } cout<<a<<" raised to power "<<b<<" is "<<res; return 0; }

Output

2 raised to power 3 is 8

### Method 2-Using Recursion

**Raise to power c++: **We know that recursion is a method or procedure in which a method calls itself again and again. Let see how we can apply recursion here.

We can write 2^3 as 2*(2^2) and this as 4*(2). That’s how recursion work here. For better understanding let’s write code for this.

#include <iostream> using namespace std; int power(int a,int b) { if(b==0) { return 1; } return a*power(a,b-1); } int main() { int a=2,b=3,res; res=power(a,b); cout<<a<<" raised to power "<<b<<" is "<<res; return 0; }

Output

2 raised to power 3 is 8

Here we see that we calculate power function again and again. So this is how we use recursion to calculate power.

### Method 3-Using inbuilt method pow()

**How to raise a number to a power in c++: **In c++ we have an inbuilt method pow() which contains two arguments a and b where a is the number and b is the power. This function returns a raise to the power b. Here we must remember that this function is contained in another library in c++ and not in iostream so instead of including iostream we can include bits/stdc++.h. Let write code for this.

#include <bits/stdc++.h> using namespace std; int main() { int a=2,b=3,res; res=pow(a,b); cout<<a<<" raised to power "<<b<<" is "<<res; return 0; }

Output

2 raised to power 3 is 8

So these are the methods to calculate the power of numbers in c++.