Recursive Power Calculation in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to calculate the result of a given number raised to the power of n using recursion in C programming.

Create a C file

Create a new file named main.c in the ~/project/ directory. This is where we will write our C code.

Declare the function prototype

The power() function takes two integers as input and returns the value after performing the power operation.

int power(int base, int exponent);

Define the power() function

The power() function performs the power operation by calling itself recursively. If the exponent is equal to zero, it returns 1. Otherwise, it returns the value of the base multiplied by the result of calling power() function with the base and one less than the exponent.

int power(int base, int exponent)
{
    if(exponent == 0) // Base case
        return 1;
    else
        return base * power(base, exponent - 1); // Recursive case
}

Get user input and call the power() function

Get the base and exponent from the user using the scanf() function and then pass them as arguments to the power() function. Finally, display the result using printf() function.

int main()
{
    int base, exponent, result;

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

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

    result = power(base, exponent);

    printf("%d^%d = %d", base, exponent, result);

    return 0;
}

Compile and Run the code

Save the changes and compile the program using the gcc compiler as follows:

gcc main.c -o main

Now, run the program by typing the following command on the terminal:

./main

Output

The output will display the result of raising the base to the exponent that the user entered.

Summary

In this lab, we have learned how to calculate a number raised to the power of n using recursion in C programming. We achieved this by using a recursive function that calls itself until it reaches the base case, where the exponent equals zero, then it returns the value 1. We stored the values we got from the recursive function in a variable and displayed it to the user using the printf() function.

The power() function can be used to raise any number to a given power in C programming.

Other C Tutorials you may like