C Program

Write a program using recursion to find power of a number

#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:

  1. Header File:

    • #include <stdio.h>: This allows the use of printf for output and scanf for input.
  2. The power Function:

    • This function calculates the power of a number x raised to y (i.e., x^y) using recursion.
    • Base Case: When y == 0, the function returns 1 because any number raised to the power of 0 is 1.
    • Recursive Case: Otherwise, the function multiplies x by the result of power(x, y-1). This reduces the problem to calculating x^(y-1) until the base case is reached.
  3. Main Function:

    • It prompts the user to enter the values of n (base) and m (exponent).
    • It then calls the power function to calculate n^m and stores the result in k.
    • Finally, it prints the result using printf.
Output:
Enter the value of n and m
3
5
The value of nm
for n=3 and m=5 is 243 

Team Educate

About Author

Leave a comment

Your email address will not be published. Required fields are marked *

You may also like

C program to test whether a given identifier is valid or not
C Program

C Program to Test Whether a Given Identifier is Valid or Not

Rules for Valid Identifiers in C: The identifier must begin with a letter or an underscore (_). It cannot start
C program to test whether a given identifier is valid or not
C Program Compiler Design

C program to implement simple code generator

ALGORITHM:1. Start2. Get address code sequence.3. Determine current location of 3 using address (for 1st operand).4. If current location not