C Program to calculate x^n - program to compute pow(x,n)


January 8, 2023, Learn eTutorial
2128

In this C program, we have to calculate 'x raise to n' where 'x' and 'n' are given by users. For doing that we are using a function recursively pow(x,n). For example, if 'x' is equal to 2 and 'n' is 3, then the result will be 8. in this function we do the calculation separately and return " (pow(pow(x,n/2),2));" for even and return "(x*pow(x, n-1))".

What is a recursive function?

A recursive function is a function that calls itself until the exit condition is met. Hence the same function is called different times by themselves.

What is the pow() function?

The function pow() is used to calculate the power raised of a number, defined in the math library. The syntax of the pow() function is given below. 

double pow(double a double b) 

  • The pow() calculates the number 'a' raise to 'b'. where 'a' and 'b' are user inputs.

ALGORITHM

STEP 1: Include the header files for using functions that are built-in in C.

STEP 2: Declare the variables 'x, n, xpown' as a Long integer.

STEP 3: Declare the function long int pow(int x, int n).

STEP 4: Read the values of X and N from the user.

STEP 5: Call the Function xpown = pow (x,n).

STEP 6: Display X to the Power N is xpown.


Function long int pow(int x, int n)

STEP 1: Check if n==1 if true then return(x).

STEP 2: Else check if n%2 == 0 then return (pow(pow(x,n/2),2))  else do step 3.

STEP 3: Return (x*pow(x, n-1)).


To find the power of a number, we are using the below concepts in C. We recommend referring those for a better understanding

C Source Code

                                          #include <stdio>
#include <math.h>

void main() {
  long int x, n, xpown;
  long int power(int x, int n);
  printf("Enter the values of X and N\n"); /* accepts the user input */
  scanf("%ld %ld", & x, & n);
  xpown = power(x, n);
  printf("X to the power N = %ld\n");
}
/*Recursive function to compute the X to power N*/
long int power(int x, int n) {
  if (n == 1)
    return (x);
  else if (n % 2 == 0)
    return (pow(power(x, n / 2), 2)); /*use this when the n i even*/
  else
    return (x * power(x, n - 1)); /* if n is odd*/
}
                                      

OUTPUT

Enter the values of X and N
2 5
X to the power N = 32

RUN2

Enter the values offX and N
4 4
X to the power N ==256

RUN3

Enter the values of X and N
5 2
X to the power N = 25

RUN4

Enter the values of X and N
10 5
X to the power N = 100000