This is a simple program to find the factorial of a number. Factorial of a number is the product of numbers from 1 to that number. For instance, factorial of 4 is

*4 * 3 * 2 * 1 = 24*.

In this program we asks the user for an input. Before processing we check whether the number is less than 1, because a number less than 1 doesn’t have a factorial. Next we reduce the number until it becomes 1 and multiply the factorial with each number. Here is the program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include<iostream> using namespace std; int main() { int num,fact=1; cout<<"Enter a number :"; cin>>num; /* Check if user entered a number less than 1 */ if(num < 1) { cout<<"Please enter a natural number"; return 0; } /* Calculate the factorial */ while(num > 0) { fact *= num; num -= 1; } /* Print the result */ cout<<"Factorial is "<<fact; return 0; } |