Recursive Function to Calculate Factorial of a Number in C++
In this exercise, you will implement a recursive function in C++ that calculates the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and defined as:
n! = n × (n-1) × (n-2) × ... × 1
Recursion is a programming technique where a function calls itself to solve a smaller instance of the same problem. Factorials are a classic use case for practicing recursion and help reinforce your understanding of function calls, base cases, and recursion trees.
Implementation Details
1. The Base Case
Every recursive function needs a stop condition. If n == 0, we return 1. Without this, the function would call itself infinitely.
2. Recursive Call
For any number n > 0, the function returns n * factorial(n - 1), breaking the problem down into smaller steps.
3. User Validation
It is important to check if the input is negative, as factorials are only defined for non-negative integers.
Logic Tip:
Factorial results grow extremely fast. For values of n > 12, an int may overflow. Consider using long long for larger numbers.
Objective
- 1. Create a function named
factorialthat takes an integer as input. - 2. Use an
ifstatement to define the base case (n=0). - 3. Return
nmultiplied by the recursive callfactorial(n - 1). - 4. Validate the input in
main()to prevent negative values.
Example C++ Exercise
#include <iostream>
using namespace std;
// Recursive function to calculate the factorial of a number
int factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
}
return n * factorial(n - 1); // Recursive call
}
int main() {
int number;
// Ask the user to enter a number
cout << "Enter a non-negative integer: ";
cin >> number;
// Check if the number is negative
if (number < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
// Call the recursive factorial function and print the result
int result = factorial(number);
cout << "Factorial of " << number << " is: " << result << endl;
}
return 0;
}
Example Output:
Factorial of 5 is: 120