C Program to Find X^n Using Recursion
Write a C program to calculate the power(X^n) using recursion.
- The power() function uses recursion to compute x^n by repeatedly multiplying x.
- The base case returns 1 when the exponent n is 0, since any number to the power of 0 is 1.
- For positive n, the function multiplies x with the result of power(x, n-1).
- For negative n, it computes 1 / power(x, -n) to handle inverse powers.
Example : pgm.c
#include <stdio.h> // Recursion function to calculate x^n double power(double x, int n) { if (n == 0) return 1; else if (n > 0) return x * power(x, n - 1); else // Handle negative powers return 1 / power(x, -n); } int main() { double base; int exponent; printf("Enter base (x): "); scanf("%lf", &base); printf("Enter exponent (n): "); scanf("%d", &exponent); printf("%.2lf^%d = %.5lf\n", base, exponent, power(base, exponent)); return 0; }
Output :
Enter base (x): 2
Enter exponent (n): 3
2.00^3 = 8.00000
Enter exponent (n): 3
2.00^3 = 8.00000