Table of Contents
Introduction
In this program, you will learn to calculate the factorial of a number entered by the user.
The factorial of a positive integer ‘x’ is 1*2*3*4*……..*x.
For example, Factorial of 5 is (! is the symbol for factorial):
5! =5*4*3*2*1=120
Similarly, Factorial of 7 is
7! =7*6*5*4*3*2*1=5040
Factorial of negative numbers don’t exist.
Factorial of 0 and 1 is 1.
What is the use of this program?
It is easy to calculate the factorial up to certain values, but it is difficult to calculate factorial like 100! , 500! etc. A small code written in C++ will make this task quite easy.
To understand this example, you should know about the following C++ programming topics:
1. Data types
2. Operators
3. if-else statement
4. for loop
Program
#include<iostream> using namespace std; int main() { int n; cout<<"Enter a positive integer: "; cin>>n; int fact=1; // fact to store factorial value if(n<0) // if 'n' is negative { cout<<"Factorial of entered value doesn't exist."; } else { for( int i=1;i<=n;i++) { fact=fact*i; } } cout<<"Factorial of "<<n<<" is "<<fact; return 0; }
Output
Explanation
In the above program, we have to calculate the factorial of ‘n’.
The user is asked to enter the value of ‘n’.
Now we have three conditions, either ‘n’ is a positive integer or ‘n’ is 0, or ‘n’ is a negative integer. if-else statements are used to check all these conditions.
If the value of ‘n’ is less than 0, then the ‘if’ block will be executed.
Otherwise, the ‘else’ block will be executed.
for (int i=1; i<=n; i++)
‘i’ will start from 1 and iterate until it reaches ‘n’.
‘fact’ variable is initialized with 1. When the value of ‘i’ is 1, the statement
fact=fact*i; will return 1*1=1
Thus, fact=1
‘i’ is incremented, and now its value is 2
fact=fact*i; will return 1*2=2
Thus, fact=2
i’ is incremented, and now its value is 3
fact=fact*i; will return 2*3=6
Thus, fact=6
At the end, when the value of ‘i’ reaches 6, then
fact=fact*i; will return 120*6=720
thus fact=720
now ‘i’ is updated to 7, which will terminate the loop.
0 Comments