Factorial of a Number in C++ using For Loop

In this C++ programming tutorial we will see the program on Factorial of a Number in C++ using For Loop. In this program we will simple take input number from user of which the factorial is to be calculated. then we will use the for loop control structure to perform iterations and calculate factorial and store the result in another variable named factorial and display its value to the user.

For any positive number n, it’s factorial is given by:
factorial = 1*2*3…*n

Factorial of a Number in C++ using For Loop
#include <iostream>
using namespace std;

int main() {
    int i, n, factorial = 1;

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

    for (i = 1; i <= n; ++i) {
        factorial *= i;   // factorial = factorial * i;
    }
    cout<< "Factorial of "<<n<<" = "<<factorial;
    
	return 0;
}
Output
Enter a positive integer: -5
Factorial of 5 = 120

Leave a Reply

Your email address will not be published. Required fields are marked *