C++ Program to Factorial Using Recursion with Explanation
C++
Hard
Functions
45 views
1 min read
181 words
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around factorial, recursion, function. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Calculate factorial using recursive function (5! = 5×4×3×2×1)
Real Life: Understanding how functions can call themselves.
Input Format
An integer N.
Output Format
Factorial of N.
Constraints
• N ≥ 0
• Use recursion
• Result fits in data type used
Concept Explanation
Factorial of a number means multiplying the number by all smaller positive numbers till 1.
A recursive function solves it by calling itself with a smaller value.
Step-by-Step Logic
1.Define a recursive function fact(N).
2.Base case:
• If N == 0 or N == 1, return 1.
3.Recursive case:
• Return N * fact(N - 1).
4.Each function call reduces N by 1.
5.Calls stop when base case is reached.
6.Final result is returned to main() and printed.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
int factorial(int n) {
if(n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}
void function_q11_factorial_recursion() {
int num = 6;
int result = factorial(num);
cout << "Factorial of " << num << " is: " << result << endl;
}
Common Mistakes
- Starting the loop from 0 (factorial becomes 0).
- Not initializing the factorial value as 1.
- Using int for large n causing overflow.
- Printing extra spaces/newlines that break format.
Solution Guide
Problem
Calculate factorial using recursive function (5! = 5×4×3×2×1)
Real Life: Understanding how functions can call themselves.
Input / Output
Constraints
• N ≥ 0
• Use recursion
• Result fits in data type used
Explanation
Concept Explanation
Factorial of a number means multiplying the number by all smaller positive numbers till 1.
A recursive function solves it by calling itself with a smaller value.
Step-by-Step Explanation
1.Define a recursive function fact(N).
2.Base case:
• If N == 0 or N == 1, return 1.
3.Recursive case:
• Return N * fact(N - 1).
4.Each function call reduces N by 1.
5.Calls stop when base case is reached.
6.Final result is returned to main() and printed.
Details
Common Mistakes
- Starting the loop from 0 (factorial becomes 0).
- Not initializing the factorial value as 1.
- Using int for large n causing overflow.
- Printing extra spaces/newlines that break format.
Official Solution
int factorial(int n) {
if(n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive call
}
void function_q11_factorial_recursion() {
int num = 6;
int result = factorial(num);
cout << "Factorial of " << num << " is: " << result << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!