C++ Program To Find Factorial Of A Number Using Iteration - C++ Programming Tutorial
C++ Course / C++ Programs / C++ Program To Find Factorial Of A Number Using Iteration

C++ Program To Find Factorial Of A Number Using Iteration

BLUF: Mastering C++ Program To Find Factorial Of A Number Using Iteration is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Program To Find Factorial Of A Number Using Iteration

C++ is renowned for its efficiency. Learn how C++ Program To Find Factorial Of A Number Using Iteration enables low-level control and high-performance computing in the tutorial below.

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:

Example

#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:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience