#include <stdio.h>
// Function to calculate the power of a number using recursion
int power(int x, int y)
{
if (y == 0) // Base case: any number raised to the power of 0 is 1
{
return 1;
}
else // Recursive case: multiply x by power of (x, y-1)
{
return (x * power(x, y - 1));
}
}
int main()
{
int n, m, k;
// Ask the user to enter the base (n) and the exponent (m)
printf("Enter the value of n and m: ");
scanf("%d %d", &n, &m);
// Calculate n raised to the power of m
k = power(n, m);
// Output the result
printf("The value of n^m for n=%d and m=%d is %d\n", n, m, k);
return 0; // Return 0 to indicate successful execution
}
Explanation of the Code:
Header File:
#include <stdio.h>
: This allows the use ofprintf
for output andscanf
for input.
The
power
Function:- This function calculates the power of a number
x
raised toy
(i.e.,x^y
) using recursion. - Base Case: When
y == 0
, the function returns1
because any number raised to the power of0
is1
. - Recursive Case: Otherwise, the function multiplies
x
by the result ofpower(x, y-1)
. This reduces the problem to calculatingx^(y-1)
until the base case is reached.
- This function calculates the power of a number
Main Function:
- It prompts the user to enter the values of
n
(base) andm
(exponent). - It then calls the
power
function to calculaten^m
and stores the result ink
. - Finally, it prints the result using
printf
.
- It prompts the user to enter the values of
Output: Enter the value of n and m 3 5 The value of nm for n=3 and m=5 is 243