# C Program to Calculate Pow (x,n)

This is a C Program to compute the value of x ^ n.

Problem Description

This C Program computes the Value of X ^ N.

Problem Solution

The program uses power function defined in math library.

Program/Source Code

Here is source code of the C program to computes the Value of X ^ N. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

```/*
* C program to compute the value of X ^ N given X and N as inputs
*/
#include <stdio.h>
#include <math.h>

long int power(int x, int n);

void main()
{
long int x, n, xpown;

printf("Enter the values of X and N \n");
scanf("%ld %ld", &x, &n);
xpown = power(x, n);
printf("X to the power N = %ld\n", xpown);
}
/*  Recursive function to computer the X to power N */
long int power(int x, int n)
{
if (n == 1)
return(x);
else if (n % 2 == 0)
/*  if n is even */
return (pow(power(x, n/2), 2));
else
/*  if n is odd */
return (x * power(x, n - 1));
}```
Program Explanation

In this C program, library function pow() defined in <math.h> header file is used to compute mathematical functions. We are reading two integer values using ‘x’ and ‘n’ variables respectively and passing it to power() function to compute X ^ N.

The function power() uses recursion to compute the value.

In the power() function, if n equals 1, we return the value x to the calling function main(). If n is even, then we are using math library pow() function to

If condition statement is used to check the value of ‘n’ variable is equal to 1. If the condition is true, execute the statement. Otherwise, if the condition is false, execute the elseif conditional statement. Compute the modulus of n variable value by 2 and check the value is equal to zero, if the condition is true then it will execute the statement. Otherwise, if the condition is false execute the else statement.

Note: Join free Sanfoundry classes at Telegram or Youtube
Runtime Test Cases
```
\$ cc pgm55.c -lm
\$ a.out
Enter the values of X and N
2 5
X to the power N = 32```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms