Introduction:

This C program calculates the power of a number using a recursive function. By accepting a base and an exponent from the user, the program computes the result of raising the base to the specified power through repeated multiplication. Recursion is a fundamental programming technique that allows a function to call itself, providing an elegant solution to problems like exponentiation.

#include <stdio.h>

/*
 * Program to calculate the power of a number using recursion.
 * This program takes a base and an exponent as input and computes
 * the result of raising the base to the power of the exponent
 * using a recursive function.
 */

// Recursive function to calculate power
int power(int base, int exponent) {
    // Base case
    if (exponent == 0) {
        return 1; // Any number to the power of 0 is 1
    }
    // Recursive case
    return base * power(base, exponent - 1);
}

int main() {
    int base, exponent;

    printf("Enter the base: ");
    scanf("%d", &base); // Read base input

    printf("Enter the exponent: ");
    scanf("%d", &exponent); // Read exponent input

    int result = power(base, exponent);
    printf("%d raised to the power of %d is: %d\n", base, exponent, result);

    return 0;
}

Input/Output Block:

Input:

  • The user is prompted to enter the base and the exponent.

Example Input:

Enter the base: 2
Enter the exponent: 3

Output:

  • The program outputs the result of the base raised to the exponent.

Example Output:

2 raised to the power of 3 is: 8

Conclusion:

The power calculation program effectively demonstrates the use of recursion in C to solve problems involving exponentiation. By breaking down the problem into smaller subproblems, the program provides a clear and concise method for computing powers. This approach not only reinforces the concept of recursion but also illustrates its practical application in mathematical computations. Overall, the program serves as a valuable tool for learning about recursive algorithms and their implementation in C.

Leave a Reply

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

Verified by MonsterInsights