Write a program to find the factorial of a given number using while loop
This post will cover the topics on how to find the factorial value of a given number, Write a C program to find factorial of a given number, use of While Loop, how to use while loop, learn C language, code for calculating factorial.
In the following C code, we have taken the number as input value by using a built-in function scanf() and store the value in variable n. Don't know about scanf () I suggest you go to this post first
We have taken a variable named as fact in which we going to store the factorial value and its type is a long integer type. Initially, the value of fact is set to 1 and then we have used while loop.
# Use of While Loop :
Now it is the most interesting part of the C language.
While Loop as the name suggests it is a loop, now in C language loop is used to execute some specific block of code multiple times under some condition. The structure of a while loop is like this
While(check if the condition is true )
{
body of while loop
}
As long as the condition is true the loop body will be executed if the condition becomes false at a point of time then the body of the loop will no longer be executed and the program control will go outside the loop. In the following code, the while loop we are using have the condition i>0
it means as long as the value of "i" is greater than zero the body will be executed.
If you give input 7 then as the following code suggests that the initial value of i is 7 and it it will enter in the loop as a condition 'i>0 ' is satisfied now it will execute the loop body.
In First step, the statement fact= fact*i; will execute and the value of the variable fact will become 1* 7 (i.e 7) after that the statement i=i-1; will execute and the value of i will decrease to 7-1 (i.e 6)
In the second step, it will check the condition of while loop again and as the condition i>0 is satisfied then again the loop body will execute similarly this time the value of the variable fact will become 7* 6 (i.e 42) and after that the statement i=i-1; will execute and the value of i will decrease to 6-1 (i.e 5)
And then in the next step Is similar to previous steps it will go on until the value of i became zero.
When the value of i becomes zero then the Loop condition will not be satisfying anymore so then the program control will go outside of the loop and will execute further statement, in this case, it will print The Factorial of 7 is : 5040
This is the main code you can copy the this code
#include<stdio.h>
void main()
{
int n;
long int fact; /* n is the number whose factorial we have to find and fact is the factorial */
scanf("%d",&n);
fact=1;
int i=n;
while(i>0)
{
fact= fact*i;
i=i-1;
}
printf("The Factorial of %d is : %ld",n,fact);
}
7 | The Factorial of 7 is : 5040 |
Recommended posts:
0 Comments