C PROGRAMMING PROGRAM • FUNCTIONS & RECURSION
Calculate Power Using Recursion
Learn how to calculate power using recursion using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
3 5
Sample output
Result = 243
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Result = 243
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Recursively compute half the exponent and square it, multiplying by the base only for odd exponents.
- 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.
