Factorial of a number

Algorithm,Flowchart and C Program to find factorial of a number 



Algorithm:
step 1:start
step 2:Declare i,n,fact
step 3:print "enter a number"
step 4:input n 
step 5:initialize fact=1,i=1
step 6:if i>=n then goto step 
step 7:i=i+1
step 8:goto step 6
step 9:print fact
step 10:stop
 
Flowchart     
                     
 
Code

#include <stdio.h>

int main() {
    int fact=1;
    int n;
    printf("Enter a Number:");
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        fact=fact*i;
    }
    printf("Factorial of %d is %d",n,fact);
}

Sample Input and Output:

Enter a Number:4
Factorial of 4 is 24

 

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.

If you any have doubt,suggestion regarding this post or website then feel free to share with us.
 
If you have learned something new from this post then share this post with your family and
friends.
 
Happy Learning :)😎  


2 Comments

Previous Post Next Post