Power Function Recursive
C
Easy
3 views
Problem Description
Create a recursive function to calculate x^n. If n is negative, return 1/x^|n|. If n=0, return 1. Track the depth of the recursion.
Official Solution
#include <stdio.h>
/* Recursive power function */
double power(double x, int n, int depth) {
printf("Recursion depth %d: power(%.2f, %d)n", depth, x, n);
/* Base case */
if (n == 0)
return 1;
/* Negative power */
if (n < 0)
return 1 / power(x, -n, depth + 1);
/* Positive power */
return x * power(x, n - 1, depth + 1);
}
int main() {
double x;
int n;
printf("Enter value of x: ");
scanf("%lf", &x);
printf("Enter value of n: ");
scanf("%d", &n);
double result = power(x, n, 1);
printf("nResult: %.2f^%d = %.5fn", x, n, result);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!