1. Introduction
Factorial is a fundamental concept in mathematics, denoted as n! (read as "n factorial"). It is the product of all positive integers from 1 to n. For instance, the factorial of 5 (5!) is 5 x 4 x 3 x 2 x 1 = 120. The factorial function grows rapidly, meaning factorials of even modestly large numbers are enormous. In this blog post, we will develop a C++ program that computes the factorial of a given number using recursion.
2. Program Overview
Recursion is a technique in programming where a function calls itself. For computing factorials, recursion proves useful. The factorial of 0 is 1, and the factorial of any positive number n is n multiplied by the factorial of n-1. We can express this as:
0! = 1 n! = n x (n-1)!
Our program will:
1. Prompt the user to enter a number.
2. Invoke a recursive function to compute the factorial.
3. Display the result.
3. Code Program
#include <iostream>
using namespace std;
// Recursive function to calculate factorial of a number
long long factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n <= 1)
return 1;
// Recursive case: n! = n x (n-1)!
else
return n * factorial(n - 1);
}
int main() {
int num;
// Prompt user for input
cout << "Enter a positive integer: ";
cin >> num;
// Display the result
cout << "Factorial of " << num << " = " << factorial(num);
return 0; // Indicate successful program termination
}
Output:
Enter a positive integer: 5 Factorial of 5 = 120
4. Step By Step Explanation
1. Headers and Namespace: We start by including the iostream library, essential for input-output operations, and declare the use of the standard namespace.
#include <iostream>
using namespace std;
2. Recursive Factorial Function: The function factorial calculates the factorial of an integer n. It has a base case for n values of 0 or 1, returning 1. For other values, it multiplies n with the factorial of n-1.
// Recursive function to calculate factorial of a number
long long factorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n <= 1)
return 1;
// Recursive case: n! = n x (n-1)!
else
return n * factorial(n - 1);
}
3. Main Function: This is where the program begins its execution. We prompt the user for an integer input, compute the factorial using the recursive function, and then display the result.
int main() {
4. User Input: We use cout to prompt the user and cin to receive their input.
// Prompt user for input
cout << "Enter a positive integer: ";
cin >> num;
5. Factorial Calculation: We call the recursive function factorial to compute the value.
// Display the result
cout << "Factorial of " << num << " = " << factorial(num);
6. Program Termination: The program concludes its execution with a return value of 0.
return 0; // Indicate successful program termination
Comments
Post a Comment
Leave Comment