C program to generate the value of x power n using recursive function

CServer Side ProgrammingProgramming

Problem

Compute the value of xn , where x and n both are the inputs given by the user at runtime

Solution

The solution to generate the value of x power n by using the recursive function in C programming language is as follows −

The logic to find xn is mentioned below −

//Calling function:
Xpow=power(x,n);
//Called function:
if (n==1)
   return(x);
else if ( n%2 == 0)
   return (pow(power(x,n/2),2)); /*if n is even*/
else
   return (x*power(x, n-1));

Algorithm

Refer an algorithm given below to generate the value of x power n by using the recursive function.

Step 1 − Read long int variables

Step 2 − Declare function prototype

Step 3 − Call function

Xpown=power(x,n) goto step 5

Step 4 − Print xpown

Step 5 − Called function

   Step 5.1 − if (n==1)

      Step 5.1.1 − return(x)

   Step 5.2 − Else if (n%2 == 0)

      Step 5.2.1 − Return (pow(power(x,n/2),2)); /*if n is even*/

   Step 5.3 − Else

      Step 5.3.1 − Return (x*power (x, n-1)); /* if n is odd*/

Program

Following is the C program to generate the value of x power n by using the recursive function

#include <stdio.h>
#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");
   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)
      return (pow(power(x,n/2),2)); /*if n is even*/
   else
      return (x*power(x, n-1)); /* if n is odd*/
}

Output

When the above program is executed, it produces the following result −

Enter the values of X and N:
5 4
X to the power N = 625
raja
Published on 01-Sep-2021 12:56:06
Advertisements