C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION

Calculate Power Using Recursion

Learn how to calculate power using recursion using a clear C program.

IntermediateRecursionExponentiation by squaringDivide and conquer

PROBLEM UNDERSTANDING

Input and expected output

Sample input
3 5
Sample output
Result = 243

COMPLETE C PROGRAM

Complete C implementation

power-recursion.c
Open in compiler
#include <stdio.h>

long long power(long long base, unsigned int exponent)
{
    if (exponent == 0) return 1;
    long long half = power(base, exponent / 2);
    if (exponent % 2 == 0) return half * half;
    return base * half * half;
}

int main(void)
{
    long long base;
    unsigned int exponent;

    printf("Enter integer base and non-negative exponent: ");
    scanf("%lld %u", &base, &exponent);
    printf("Result = %lld\n", power(base, exponent));
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Result = 243
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Recursively compute half the exponent and square it, multiplying by the base only for odd exponents.
  3. Display the computed result.

Recursively compute half the exponent and square it, multiplying by the base only for odd exponents.

EFFICIENCY

Time and space complexity

Time complexity

O(log n)

Auxiliary space

O(log n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.