Challenge: Power with Recursion
Completed
Write a recursive function int power(int base, int exp) that returns base to the power exp (exp ≥ 0), using power(base, exp) = base * power(base, exp - 1). Read base and exp and print the result.
Input
Two integers: base and exp.
Output
The result.
Example
Input
2 10
Output
1024
Editor
C
Hints
The base case: anything to the power 0 is 1.
Otherwise return base * power(base, exp - 1).
Solution explanation
Each call does one multiplication and passes a smaller exponent on, until the exponent reaches 0.
Show solution
#include <stdio.h>
int power(int base, int exp) {
if (exp == 0) {
return 1;
}
return base * power(base, exp - 1);
}
int main() {
int base, exp;
scanf("%d %d", &base, &exp);
printf("%d\n", power(base, exp));
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module