Home > Backend Development > C++ > 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
Release: 2023-08-25 22:33:09
forward
1922 people have browsed it

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));
Copy after login

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
Copy after login

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*/
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template