C program to find power of a number using recursion

Write a C program to input a number from user and find power of given number using recursion. How to find power of a number using recursive function in C programming. Logic to find power of a number using recursion in C programming.

Example

Input

Input base number: 5
Input power: 2

Output

2 ^ 5 = 25

Required knowledge

Basic C programming, If else, Functions, Recursion

Must know -

Declare recursive function to find power

Recursive function to calculate power

Above is the mathematical definition of recursive function to find power of a number. The function accepts two numbers i.e. x and y and calculates x ^ y.

Let us now transform the above mathematical function in C programming context.

  1. First give a meaningful name to our recursive function say pow().
  2. The function must accept two numbers i.e. base and exponent and calculate its power. Hence, take two parameters for base and exponent, say pow(double base, int exponent);.
  3. Finally the function should return base ^ exponent i.e. a double type value.

The final function declaration to calculate power is - double pow(double base, int exponent);.

Logic to calculate power of a number using recursion

After declaring pow() function its time to define logic to find power recursively. There can be three cases while calculating power of a number.

  • If exponent is 0, then power is 1. This is the base condition of our recursive function.
  • If exponent is negative, then power is 1 / (x ^ -y). Which uses recursive call to pow() function for computing the value of (x ^ -1) i.e. 1 / pow(base, -expo).
  • If exponent is positive, then calculate power normally using x ^ y. Computing x ^ y also makes a recursive call i.e. base * pow(base, expo - 1)

Let us combine all three conditions in a single recursive function.

Program to find power of a number using recursion

/**
 * C program to find power of a number using recursion
 */

#include <stdio.h>


/* Power function declaration */
double pow(double base, int expo);


int main()
{
    double base, power;
    int expo;
    
    /* Input base and exponent from user */
    printf("Enter base: ");
    scanf("%lf", &base);
    printf("Enter exponent: ");
    scanf("%d", &expo);
    
    // Call pow function
    power = pow(base, expo); 
    
    printf("%.2lf ^ %d = %f", base, expo, power);
    
    return 0;
}


/**
 * Calculate power of any number.
 * Returns base ^ expo
 */
double pow(double base, int expo)
{
    /* Base condition */
    if(expo == 0)
        return 1;
    else if(expo > 0)
        return base * pow(base, expo - 1);
    else
        return 1 / pow(base, -expo);
}

Output

Enter base: 2
Enter exponent: 5
2.00 ^ 5 = 32.000000

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>