Write a C++ program that inputs a positive number form user and program will display its factorial. For example (factorial of 4 = 1x2x3x4 which equals to 24)
#include <iostream>
//factorial function
unsigned int fact(unsigned int n) {
if (n <= 1) //edge case, factorial of 0 is 1
return 1;
return n * fact(n - 1); //recursive call with n reduced by one
}
int main() {
unsigned int num;
std::cout << "Enter positive number: ";
std::cin >> num;
std::cout << "Factorial of " << num << " is " << fact(num) << std::endl;
return 0;
}
Comments
Leave a comment