Certainly! Here's a simple C++ program that calculates the factorial of a number using a for
loop:
#include <iostream>
int main() {
int n;
unsigned long long factorial = 1;
std::cout << "Enter a positive integer: ";
std::cin >> n;
if (n < 0) {
std::cout << "Factorial of a negative number doesn't exist.";
} else {
for(int i = 1; i <= n; ++i) {
factorial *= i;
}
std::cout << "Factorial of " << n << " = " << factorial;
}
return 0;
}
This program first prompts the user to enter a positive integer. Then, it uses a for
loop to multiply the numbers from 1 up to the entered number to calculate the factorial. If the user enters a negative number, it outputs an appropriate message. Remember, the factorial of 0 is 1.
Top comments (1)
Thanks that's home helpful information.
But you could've made it less obvious that you used chatgpt 😂