C Program To Calculate The Power Using Recursion

In this post, we will learn how to calculate the power using recursion in C Programming language.

C Program To Calculate The Power Using Recursion

A Power is the product of multiplying a number by itself. The base number tells what number is being multiplied and the exponent tells how many times the base number is being multiplied.

This program will take base and exponent as an input from the user and calculate the power of the number using a recursive function.

So, without further ado, let’s begin this tutorial.

Contents

C Program To Calculate The Power Using Recursion

// C Program To Calculate The Power Using Recursion
#include <stdio.h>
int calculatePower(int base, int power){
    if (power != 0)
        return (base * calculatePower(base, power -1));
    else 
        return 1;
}

int main(){
    int base, power;
    
    // Asking for Input
    printf("Enter the base: ");
    scanf("%d", &base);
    printf("Enter the power: ");
    scanf("%d", &power);
    
    printf("%d raised to %d is %d", base, power, calculatePower(base, power));
    return 0;
    
}

Output

Enter the base: 2
Enter the power: 5
2 raised to 5 is 32

How Does This Program Work ?

int calculatePower(int base, int power){
    if (power != 0)
        return (base * calculatePower(base, power -1));
    else 
        return 1;
}

This is a recursive user defined function. If the power is zero, then the power of the number is 1 because any number raised to power 0 is 1.

If the power is not zero, then the recursive function calls itself and calculates the power of the number.

    int base, power;

We have declared two int data type variables named as base and power.

    // Asking for Input
    printf("Enter the base: ");
    scanf("%d", &base);
    printf("Enter the power: ");
    scanf("%d", &power);

Then, the user is asked to enter the values of base and power.

    printf("%d raised to %d is %d", base, power, calculatePower(base, power));

In the main function, the recursive function is called and the power of number is displayed to the user.

Conclusion

I hope after going through this post, you understand how to calculate the power of a number using recursion in C Programming language.

If you have any query regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published.