Input a random positive integer.
Using a for() loop, generate the factorial value of the integer and print out the result.Tip: Factorials work like this: Factorial of 5 = 1*2*3*4*5
Note that there is a special case and that is the factorial of 0 which is 1.
#include <iostream>
int facorial(int n) {
int res = 1;
for (int i=2; i<=n; i++) {
res *= i;
}
return res;
}
int main() {
int n;
std:: cout << "Enter a positive integer: ";
std::cin >> n;
std::cout << "Factorial of " << n << " is " << facorial(n);
return 0;
}
Comments
Leave a comment