C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

Recursive Function for power calculation

C Program: Recursive Function for power calculation

C

#include <stdio.h>

 

// Function declaration

long long power(int base, int exp);

 

int main() {

    int base, exponent;

 

    // Input base and exponent

    printf("Enter base: ");

    scanf("%d", &base);

    printf("Enter exponent: ");

    scanf("%d", &exponent);

 

    // Function call and display result

    printf("%d^%d = %lld\n", base, exponent, power(base, exponent));

 

    return 0;

}

 

// Recursive function to calculate power

long long power(int base, int exp) {

    if (exp == 0)

        return 1;  // Base case: any number^0 = 1

    return base * power(base, exp - 1);

}

Output

 
OUTPUT 1 :
Enter base: 2
Enter exponent: 5
2^5 = 32


OUTPUT 2 :
Enter base: 3
Enter exponent: 4
3^4 = 81


Explanation

  1. Recursive Concept
    • The function multiplies base repeatedly exp
    • Each recursive call reduces exp by 1 until it reaches 0.
  2. Base Case
    • When exp == 0, function returns 1 (mathematical rule).
  3. Recursive Step

power(2, 3)

→ 2 * power(2, 2)

→ 2 * (2 * power(2, 1))

→ 2 * (2 * (2 * power(2, 0)))

→ 2 * 2 * 2 * 1 = 8