C++ Program to Find Factorial of a Number Without Using Recursion

1. Introduction

Factorial, denoted as n!, is a fundamental mathematical operation, representing the product of all positive integers less than or equal to n. For instance, the factorial of 5 (5!) is 5 x 4 x 3 x 2 x 1 = 120. Computing factorials is a popular task in programming, serving as a means to understand control structures, particularly loops. In this post, we'll discuss a C++ program that calculates the factorial of a number without using recursion.

2. Program Overview

The program's logic is straightforward:

1. Prompt the user to input a number.

2. Use a loop to multiply numbers in decreasing order until 1.

3. Display the calculated factorial to the user.

3. Code Program

#include <iostream>
using namespace std;

int main() {
    int num;
    unsigned long long factorial = 1;  // To hold larger factorial values

    // Getting user input
    cout << "Enter a positive integer: ";
    cin >> num;

    // Factorial calculation
    for(int i = 1; i <= num; ++i) {
        factorial *= i;  // Multiplying each number with the result
    }

    cout << "Factorial of " << num << " = " << factorial;

    return 0;  // Signify successful program termination
}

Output:

For an input of 5, the program would output:
"Factorial of 5 = 120"

4. Step By Step Explanation

1. Headers and Namespace: We commence by including the I/O stream library and establishing the use of the standard namespace.

2. Main Function: This is where our program starts. Within, we declare our variables: num for holding user input and factorial initialized to 1 for computing the factorial. We use unsigned long long for factorial to manage larger factorial values.

3. User Input: The program uses cout to prompt for a number and cin to receive the entered number.

4. Factorial Logic: Utilizing a for loop, we multiply numbers in descending order till 1. The multiplication accumulates in the factorial variable.

5. Displaying the Result: The program then uses cout to display the calculated factorial.

6. Program Termination: The main function concludes and signals successful termination with a return value of 0.

Comments