C++ - Factorial of a Number
Problem Statement
Brief Description
According to the problem statement we have to write a program in C++ that will take an integer value as input from the user through the keyboard and will find the factorial of that number.
Factorial of a number is obtained by multiplying all the integer values from 1 to that that number.
Also note the following two important points in order to find the factorial of a number:
(i) Factorial is not defined for the negative numbers.
(ii) Factorial of 0 is 1 i.e. 0!=1.
For example, if the user enters 5 as input, the program will generate 120 as output since 5!=1*2*3*4*5=120.
To view Flowchart click the link given below:
Program
#include
using namespace std;
int main()
{
int num,fact=1,i;
cout<<"Enter a number: ";
cin>>num;
if(num<0)
cout<<"Factorial is not defined for the negative numbers";
else
{
for(i=1;i<=num;i++)
{
fact=fact*i; //OR fact*=i;
}
cout<<"Factorial of "<
Output
Enter a number: 5 Factorial of 5 is 120
Explanation
- 3 integer variable namely num, fact and i are declared.
- Initially 1 is stored in fact.
- The integer value entered by the user is stored in num.
- If a negative number is entered by the user, the condition num<0 is evaluated to 1(True) and the message “Factorial is not defined for the negative numbers” is displayed.
- If a number which is greater than or equal to zero is entered, the condition num<0 is evaluated to 0(False) and control goes to the else block and the statements written within else block are executed.
num | i<=num | fact=fact*i; | fact | i++ OR i=i+1 | i | Comment |
---|---|---|---|---|---|---|
5 | ----- | ----- | 1 | ----- | 1 | Initial Values |
5 | 1<=5 ↓ 1(True) | fact=1*1; | 1 | i=1+1 | 2 | Iteration 1 |
5 | 2<=5 ↓ 1(True) | fact=1*2; | 2 | i=2+1 | 3 | Iteration 2 |
5 | 3<=5 ↓ 1(True) | fact=2*3; | 6 | i=3+1 | 4 | Iteration 3 |
5 | 4<=5 ↓ 1(True) | fact=6*4; | 24 | i=4+1 | 5 | Iteration 4 |
5 | 5<=5 ↓ 1(True) | fact=24*5; | 120 | i=5+1 | 6 | Iteration 5 |
5 | 6<=5 ↓ 0(False) | ----- | ----- | ----- | ----- | For loop stops working as condition is evaluated to 0(False) |
- At first 1 is stored in i.
- The condition i<=num is evaluated.
- The condition i<=num will produce either 1(True) or 0(False) after evaluation.
- If it is 1(True), the statement written within for loop is executed and the loop continues to iterate till the condition is 1(True).
- If it is 0(False) then the loop stops working and the control goes to the statement written immediately after the loop.
- At the end of each iteration, the value of i is incremented by 1 by executing the statement i++.
- Within for loop, the value obtained in i is multiplied with the value stored in fact and the result is stored in the same variable i.e. fact.
Thus the above process generates the Factorial of the given number by multiplying all the integer values from 1 to that number.
The final result is stored in fact.
Finally the result is displayed on the output screen.