Recursive Power Function
#include <stdio.h> // Standard Input/Output library for printf and scanf
// Function Prototype (Declaration) - Best practice in C
int power(int a, int b);
// Recursive function to calculate a to the power of b (a^b)
int power(int a, int b) {
// Base Case: Any number raised to the power of 0 is 1
if (b == 0) {
return 1;
}
// Recursive Step: a^b = a * a^(b-1)
return a * power(a, b - 1);
}
// Main function
int main() {
int a;
printf("enter a: ");
// Use %d format specifier for reading an integer
scanf("%d", &a);
int b;
printf("enter b: ");
// Use %d format specifier for reading an integer
scanf("%d", &b);
// Print the result
printf("%d raised to %d = %d\n", a, b, power(a, b));
return 0; // Return 0 to indicate successful execution
}
Comments
Post a Comment