# C Program to Find Power of a Number

Power of any number bn given as b*b*…..*b (n-times). Here b is called base and n is called the exponent. Here we will write the C program to find the power of a number.

Example:-

22 = 2*2 = 4
33 = 3*3*3 = 27
53 = 5*5*5 = 125

Write a c program to find power of a number using while loops. the base number (>0) and exponent (>=0) is taken from the test cases.

C Program to Find Power of a Number using while loop

`````` #include<stdio.h>
int main()
{
int base, exponent;
long power=1;

printf("Enter base and Exponent: ");
scanf("%d %d",&base,&exponent);

while(exponent!=0)
{
power *= base; //power= power  * base
exponent--;
}

printf("Result = %ld\n", power);

return 0;
}``````

Output:-

Enter base and Exponent: 3 4
Result = 81

Explanation:-

At start base=3, exponent=4
from while loop,
4!=0 true power=1*3=3 and exponent=4-1=3
3!=0 true power=3*3=9 and exponent=3-1=2
2!=0 true power=9*3=27 and exponent=2-1=1
1!=0 true power=27*3=81 and exponent=1-1=0
0!=0 false
Finally power = 81

In the while loop, we can also use increment operators instead of the decrement operator.

C program to find x power y using for loop

Below is the C program to calculate power of a Number using for loop.

`````` #include<stdio.h>
int main()
{
int base, exponent, i;
long power=1;

printf("Enter base and Exponent: ");
scanf("%d %d", &base, &exponent);

for(i=1;i<=exponent;i++)
{
power *= base; // power=power*base
}

printf("Result = %ld\n",power);

return 0;
}``````

Output:-

Enter base and Exponent: 2 3
Result = 8
Enter base and Exponent: 25 6
Result = 244140625

Explanation:-

At start base=2, exponent=3
i=1; 1<=3 true power=1*2=2 and i++=1+1=2
i=2; 2<=3 true power=2*2=4 and i++=2+1=3
i=3; 3<=3 true power=4*2=8 and i++=3+1=4
i=4 4<=3 false
Finally power=8

Here we used the increment operator (i++), the problem also can be solved using decrement operator (i–) try it yourself.

## C Program to Find Power of a Number using pow() function

Calculation of  Power is required many times. So, for fast and easy purposes pow() function is defined under standard library function math.h

`````` #include<stdio.h>
#include<math.h>
int main()
{
int base, exponent;
long power;

printf("Enter base and Exponent: ");
scanf("%d %d", &base, &exponent);

power = pow(base,exponent);

printf("Result = %ld",power);
return 0;
}``````

Output:-

Enter base and Exponent: 2 3
Result = 8

We can do the same task using Recursion also:- Calculate Power of a Number using Recursion

If you are using Linux/Unix OS and getting an error from using pow() function then read it “undefined reference to sqrt (or other mathematical functions)” even include math.h header

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!