cplusplus
#include <iostream>
using namespace std;
int main() {
int number, factorial = 1;
cout << "Enter a positive integer: ";
cin >> number;
if (number < 0) {
cout << "Error! Factorial of a negative number is not defined.";
} else {
for (int i = 1; i <= number; ++i) {
factorial *= i;
}
cout << "Factorial of " << number << " = " << factorial;
}
return 0;
}
Explanation:
#include <iostream>
: This line includes the input-output stream header file that allows input and output operations.using namespace std;
: This line allows us to use entities likecout
andcin
without specifying thestd
namespace.int main() {...}
: The program execution starts from here. It's the main function of the program.int number, factorial = 1;
: Declares two integer variablesnumber
andfactorial
and initializesfactorial
to 1.cout << "Enter a positive integer: ";
: Prints a message asking the user to enter a positive integer.cin >> number;
: Takes user input and stores it in the variablenumber
.if (number < 0) {...}
: Checks if the entered number is less than 0.cout << "Error! Factorial of a negative number is not defined.";
: If the number is negative, displays an error message since factorial of a negative number is not defined.else {...}
: If the number is non-negative, the program enters this block.for (int i = 1; i <= number; ++i) {...}
: Starts a for loop initializingi
to 1 and iterating untili
reaches the value ofnumber
.factorial *= i;
: Multipliesfactorial
byi
in each iteration.cout << "Factorial of " << number << " = " << factorial;
: Prints the factorial value of the entered number.return 0;
: Indicates successful termination of themain()
function and the program.