#include <iostream>
using namespace std;
int factorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
int result = factorial(n);
cout << "The factorial of " << n << " is " << result << endl;
return 0;
}
In this program, we define a function factorial that takes an integer argument n and returns the factorial of n. We initialize a variable fact to 1 and loop from 1 to n, multiplying fact by the current loop variable at each iteration. This gives us the factorial of n.
In the main function, we prompt the user to enter a number and read it in using cin. We call the factorial function with the user's input as the argument and store the result in a variable result.
Finally, we print out the result using cout. The program returns 0 to indicate successful execution.
0 Comments