Algorithm,Flowchart and C Program to find factorial of a number
Sample Input and Output:
Explanation of above Program
Factorial:Factorial of a number is the product of all the integer from 1 to that number.for eg factorial of 4 can be evaluated as 1*2*3*4=24
- Steps to calculate factorial of a number
initialize the fact variable with 1.Some of You must thing that why we have initialize the variable with 1 and not 0 so read the full article your doubt will be clear.
take input from the user or directly initialize variable with literals.
Now take for loop or while loop as per convince.I am taking for loop because it is good to use for loop if we know the total no.of iteration.
fact=0
i=1
fact=fact*i
Value of fact is 0
i=2
fact=fact*2
Value of fact is 0
.....
i=n
fact=0*n
Value of fact is 0
As we can se that if we initialize fact with 0 then the factorial of any number would be 0 because multiplication of any number with 0 will be 0 which is wrong that's why we have not initialize it with 0.I thing Your doubt is clear now,if you have still any doubt then feel free to ask on comment,I will be happy to answer you.
Let's try to find factorial of 4 step by step from above program logic
Initialization
fact=1
n=4
the value of n is 4 therefore loop will iterate four times.
1st time: 1<=4
2nd time:2<=4
3rd time:3<=4
4rd time:4<=4
5<=4 is false therefore loop will stop.
1st iteration
i=1
fact=fact*i
Value of fact is 1
2nd iteration
i=2
fact=fact*i
Value of fact is 2
3rd iteration
i=3
fact=fact*i
Value of fact is 6
4th iteration
i=4
fact=fact*i
Value of fact is 24
So the Factorial of 4 is 24.
friends.
Above given example is easy to Understand to these Language. Nice 😇
ReplyDeleteNicely explained! 👏
ReplyDelete