- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C program to generate the value of x power n using recursive function
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:
"); scanf("%ld %ld", &x, &n); xpown = power (x, n); printf("X to the power N = %ld
",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
To Continue Learning Please Login
Login with Google