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
- 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
//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
cout<<"Enter the number: "; //Ask for the number.
cout<<"The factorial of the given number is: "<<factorial<<endl;
Tested in: Visual C++/Visual Studio
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