Calculate the Factorial of a Number Using a For Loop

Calculate the Factorial of a Number Using a Loop in C++

The factorial of a number $N$ (denoted as $N!$) is the product of all positive integers less than or equal to $N$. For example: $5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$.

Iterative Logic

The For Loop

A for loop is used to repeat the multiplication process exactly $N$ times, starting from 1 up to the input number.

Accumulator Variable

We initialize a factorial variable to 1. During each iteration, we update it using the *= operator.

Step-by-Step Objective

  • Prompt the user to enter a positive integer $N$.
  • Initialize an int variable named factorial to 1.
  • Use a for loop starting from i = 1 up to N.
  • Multiply the factorial variable by i in each step.
  • Display the final result to the console.

C++ Solution

factorial_loop.cpp Iterative Logic
#include <iostream>
using namespace std;

int main() {
    int N;
    long long factorial = 1; // Use long long for larger results

    cout << "Enter a positive integer: ";
    cin >> N;

    // Use a for loop to calculate the factorial
    for (int i = 1; i <= N; ++i) {
        factorial *= i; // multiply result by current index
    }

    cout << "The factorial of " << N << " is: " << factorial << endl;

    return 0;
}

Console Output:

Enter a positive integer: 5
The factorial of 5 is: 120
Flow Control & Loops
For Loop Structure Factorial Algorithm Accumulator Logic Numeric Processing C++ Basics

Share this C++ Exercise

Help others learn algorithms and loop structures in C++.

© C++ Programming Exercises. Master the art of performance coding.