Calculate the Power Using Recursion in C

Exercise:

Write a C Program to calculate the power using recursion.

Click Here to View the Solution!
#include <stdio.h>
int power(int num1, int num2);

int main() {
    int base, exp, result;
    printf("Enter base number: ");
    scanf("%d", &base);
    printf("Enter exponent: ");
    scanf("%d", &exp);
    result = power(base, exp);
    printf("%d^%d = %d", base, exp, result);
    return 0;
}

int power(int base, int exp) {
    if (exp != 0)
        return (base * power(base, exp - 1));
    else
        return 1;
}
Click Here to View the Output!
Enter base number: 8                                  
Enter power number(positive integer): 2
8^2 = 64  
Click Here to View the Explanation!
  • This program is used to calculate the power of a number by using recursion.
  • A user defined function power is declared that takes two integers as its parameters.
  • In main(), the program requests the user to enter a base number and a positive power number and stores them in the integer variables base and exp using the scanf() function.
  • The power function takes the entered base and exponent as its parameters and its output is stored in the variable result.
  • Initially, the power function is called from main with the entered integers as its parameters.
  • The power function is then initialized using an if statement which will return the power of a number only if the exp will not be equal to 0.
  • If the condition is true, the function will be called recursively, and the base will be multiplied with the power function again taking the exp one less than the original value in its parameter.
  • The final value calculated is then returned to main for printing.
%d bloggers like this: