In this program, we see a simple way to calculate the factorial of a number.

In this program,

- We use a
**for loop**for multiplying all the numbers from 1 to ‘*num*‘. - We use 3 variables:
*num*(for storing the number),*factorial*(to store the factorial of num) and*i*(to count from 1 to*num*). - We initialize variable
*factorial*to 1 and multiply it with*i*in the for loop. - So, the for loop runs till
*i*becomes equal to*num,*thus multiplying each number(in the form of*i*till*num*) with variable*factorial*gives us our factorial of the number in the variable*factorial*.

**Example**: num=3, factorial=1, i=1

Loop number:

- factorial=factorial*i i.e., factorial=1*1=1.
- factorial=factorial*i i.e., factorial=1*2=2.
- factorial=factorial*i i.e., factorial=2*3=6.

Therefore, factorial of **3**=**6**

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 |
//Variables: //int num: To save the number(user-input). //int factorial: To calculate and save the factorial of the number. #include<iostream> //Calling the Header File. int main() //Declaring the main function { using namespace std; //Tells the compiler that we'll be using all the standard C++ library functions int num,factorial=1; cout<<"Enter the number: "; //Ask for the number. cin>>num; for(int i=1;i<=num;i++) { factorial=factorial*i; } cout<<"The factorial of the given number is: "<<factorial<<endl; cin.get(); return 0; } |

Tested in: Visual C++/Visual Studio

The following two tabs change content below.

#### Lalit Mali

Lalit is a technology enthusiast, a programming lover and currently an Android fan.

#### Latest posts by Lalit Mali (see all)

- Rank Pages in a Directory by Occurrence of a Particular Word in them – Java Data Mining - October 16, 2012
- Java Data Mining: Number of occurrences of a word in a file - October 15, 2012
- Calculate factorial of a number using C++ Recursive function - October 14, 2012