Home  >  Article  >  Backend Development  >  C program to generate x raised to the nth power using recursive function

C program to generate x raised to the nth power using recursive function

PHPz
PHPzforward
2023-08-25 22:33:091895browse

C program to generate x raised to the nth power using recursive function

Problem

Calculate the value of x raised to the nth power, where x and n are both entered by the user at runtime

Solution

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

The logic to find x raised to the nth power is as follows −

//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 to the algorithm given below and use the recursive function to generate the value of x raised to the nth power.

Step 1 - Read long integer variable

Step 2 - Declare function prototype

Step 3 - Call function

Xpown=power(x,n) goto step 5

Step 4 − Print xpown

Step 5 − Call 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 an even number*/

Step 5.3 − Else

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

Program

The following is a C program that uses a recursive function to generate the nth power value of x−

#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: </p><p>");
   scanf("%ld %ld", &x, &n);
   xpown = power (x, n);
   printf("X to the power N = %ld</p><p>",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

The above is the detailed content of C program to generate x raised to the nth power using recursive function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete

Related articles

See more