A mathematical operation referred to as a factorial calculates the result of multiplying all positive integers from 1 up to a given number "n". This tutorial will demonstrate the process of calculating the factorial of a number through iteration in C++.
Understanding Factorial:
The result of multiplying all positive integers up to a non-negative integer 'n' is known as its factorial, denoted as 'n!'. Factorials are commonly used in various mathematical and combinatorial calculations. When it comes to the factorial function, the starting point is the factorial of 0, which is defined as 1.
The following simple method can be used to iteratively compute the factorial of a given number:
- Set the initial value of a variable, usually called "factorial" , to 1 to store the outcome.
- Make an iteration loop that goes from 1 to 'n' , where 'n' is the number you wish to get the factorial for.
- Multiply the current value of "factorial" by the loop counter for each iteration of the loop.
- The factorial of 'n' will be in the 'factorial' variable once the loop has finished.
Example:
Let's consider a C++ code to Calculate the factorial of a number using Iteration:
#include <iostream>
using namespace std;
// Function to calculate factorial using iteration
unsigned long long calculateFactorial(int n) {
if (n < 0) {
// Factorial is not defined for negative numbers
return 0;
}
unsigned long long factorial = 1;
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
return factorial;
}
int main() {
int n;
// Input
cout << "Enter a non-negative integer to calculate its factorial: ";
cin >> n;
// Check for negative input
if (n < 0)
{
cout << "Factorial is not defined for negative numbers." << endl;
} else {
// Calculate the factorial and display the result
unsigned long long result = calculateFactorial(n);
cout << "The factorial of " << n << " is " << result << endl;
}
return 0;
}
Output: