C program to calculate the power using recursion
Example: Program to calculate the power using recursion
#include <stdio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number(positive integer): ");
scanf("%d",&powerRaised);
result = power(base, powerRaised);
printf("%d^%d = %d", base, powerRaised, result);
return 0;
}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
else
return 1;
}
Output
Enter base number: 3 Enter power number(positive integer): 4 3^4 = 81
Example C program to calculate the power of a number using recursion:
#include <stdio.h>
// Function to calculate the power of a number using recursion
int power(int base, int exponent) {
if (exponent == 0) { // Base case: any number raised to 0 is 1
return 1;
} else {
return base * power(base, exponent - 1); // Recursive case
}
}
int main() {
int base, exponent, result;
printf("Enter the base number: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
result = power(base, exponent);
printf("%d to the power of %d is: %d\n", base, exponent, result);
return 0;
}
In this program, we define a function power()
that takes two integer arguments base
and exponent
. The function uses recursion to calculate the power of the base number raised to the exponent.
The function first checks for the base case, which is when the exponent is equal to zero. In this case, the function returns 1 since any number raised to the power of 0 is 1.
If the exponent is not equal to zero, the function enters the recursive case where it multiplies the base number by the result of the power()
function with the same base and exponent decremented by 1. This process continues until the base case is reached.
In the main()
function, we ask the user to enter the base number and exponent, call the power()
function with these inputs, and print the result.