Complementary task for topic: 10
M Nemeth · 2023-08-29 15:21:04.632218'
Recursion: Power
Recursion: Power
Write a program to calculate the power of a number using recursion! (expontent is integer)
Hint: We know that:
We have 3 cases:
exponent==0: reuslt:1
expontent positive integer: base*power(...)
exponent negative: 1/(base*power(...)
Solution
#include
// Function to calculate the power of a number using recursion
double power(double base, int exponent) {
if (exponent == 0) {
return 1;
} else if (exponent > 0) {
return base * power(base, exponent - 1);
} else {
return 1.0 / (base * power(base, -exponent - 1));
}
}
int main() {
double base;
int exponent;
printf("Enter the base: ");
scanf("%lf", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
double result = power(base, exponent);
printf("%.2lf^%d = %.2lf\n", base, exponent, result);
return 0;
}
Explanation
The user inputs the base and exponent, and the program reads them using scanf. The main function then calls the power function, passing the entered base and exponent as arguments. The power function uses recursion to calculate the power of the given base and exponent. If the exponent is 0, it returns 1 (any number raised to the power of 0 is 1). If the exponent is positive, it multiplies the base by the result of power(base, exponent - 1). If the exponent is negative, it takes the reciprocal of the result of power(base, -exponent - 1) to handle negative exponents.