C++ Program to Calculate Power Using Recursion with Explanation
C++
Medium
Functions
38 views
1 min read
179 words
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around power, recursion, raised. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Calculate x raised to power n (x^n) using recursive function.
Real Life: Like calculating compound interest repeatedly.
Input Format
Two integers:
• x (base)
• n (power)
Output Format
Value of x^n.
Constraints
• n ≥ 0
• Use recursion
• Result fits in data type
Concept Explanation
x^n means multiplying x by itself n times.
Recursion solves this by reducing the power step by step.
This is similar to compound interest, where the same operation repeats.
Step-by-Step Logic
1.Define a recursive function power(x, n).
2.Base case:
• If n == 0, return 1.
3.Recursive case:
• Return x * power(x, n - 1).
4.Each call reduces n by 1.
5.Calls stop when n becomes 0.
6.Final value is returned to main() and printed.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
int calculatePower(int base, int exponent) {
if(exponent == 0) {
return 1; // Base case
}
return base * calculatePower(base, exponent - 1); // Recursive call
}
void function_q6_power_recursion() {
int x = 2;
int n = 5;
int result = calculatePower(x, n);
cout << x << " raised to power " << n << " is: " << result << endl;
}
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Calculate x raised to power n (x^n) using recursive function.
Real Life: Like calculating compound interest repeatedly.
Input / Output
Input
Two integers:
• x (base)
• n (power)
Constraints
• n ≥ 0
• Use recursion
• Result fits in data type
Explanation
Concept Explanation
x^n means multiplying x by itself n times.
Recursion solves this by reducing the power step by step.
This is similar to compound interest, where the same operation repeats.
Step-by-Step Explanation
1.Define a recursive function power(x, n).
2.Base case:
• If n == 0, return 1.
3.Recursive case:
• Return x * power(x, n - 1).
4.Each call reduces n by 1.
5.Calls stop when n becomes 0.
6.Final value is returned to main() and printed.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
int calculatePower(int base, int exponent) {
if(exponent == 0) {
return 1; // Base case
}
return base * calculatePower(base, exponent - 1); // Recursive call
}
void function_q6_power_recursion() {
int x = 2;
int n = 5;
int result = calculatePower(x, n);
cout << x << " raised to power " << n << " is: " << result << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!