# C Program to Calculate Power of a Number

The power of a number can be defined as how many times the number is multiplied with itself. For example:

```	93= 9 X 9 X 9 = 729
25= 2 X 2 X 2 X 2 X 2 = 32
```

This can be written in the form xn. So, in this program we ask the user to input the value of x and n.

## Example 1: Calculating Power Using Loop

```#include<stdio.h>
int main()
{
int i=1, x, n, ans=1;
printf("Enter x and power n n");
scanf("%d n %d", &x, &n);

while (i<=n)
{
ans = ans*x;
i = i+1;
}

printf("%d to the power %d is %d", x, n, ans);
return 0;
}```

Here, the user is asked to enter value of x and n. Variable i is initialized to 1 as it acts as counter for the loop. And the loop is to be executed as long as i<=n as the number has to be multiplied with itself for n times. Variable ans is initialized to 1 at first as ans is stored in this variable. In the first loop,

ans = ans * x;

If the user has input value of x as 2 and n as 4 then,

ans = 1 * 2 i.e. ans =2

On the second loop,

ans = ans * x i.e. ans = 2 * 2 = 4

On the third loop,

ans = ans * x i.e. ans = 4 * 2 = 8

And, on the fourth loop,

ans = ans * x i.e. ans = 8 * 2 = 16 which is the final answer.

## Example 2: Calculating Power Using pow() Function

In C program, there is a function pow(), defined in the header file <math.h> which calculates the power of a number.

```#include<stdio.h>
#include<math.h>
int main()
{
int i=1, x, n, ans=1;
printf("Enter x and power n n");
scanf("%d n %d",&x, &n);

ans= pow (x,n);

printf("%d to the power %d is %d", x, n, ans);
return 0;
}```

### Output:

```Enter x and power n
3
4
3 to the power 4 is 81```