#include <stdio.h>
/* Write the Program in C language to find factorial of a number using while loop.*/
/* C program to to find factorial of a number using while loop.*/
#include <stdio.h>
int main()
{
int n,fact=1,i=1;
printf("\n Enter Any Number:");
scanf("%d",&n);
while(i<=n)
{
fact=fact*i;
i++;
}
printf("\n Factorial of %d=%d",n,fact);
return 0;
}
Output:
Enter Any Number
5
Factorial of 5 =120
Program Explanation:
1. In the program given above the variables n,fact and i is declared as integer variable.
fact and i variables are initialized to value 1 i.e. fact=1 , i=1.
variable n is declared as the integer whose factorial we want to find out.
2. printf("Enter Any Number\n");
prompt the user "Enter Any number" control jumps to the input function
scanf("%d",&n); and wait for the user input.
User inputs/enters number 5 which is get stored(scaned)in variable n.
3.1 control jumps to while loop and test the condition while(i<=n).
i.e. while(1<=5) which results in true, statement inside body of loop fact=fact*i and i++ executes.
Initially The value of fact=1 and i=1 the expression fact=fact*i evaluates fact=1*1 i.e. fact is assigned value 1. fact=1
next i++ executes (i=i+1) and the vaue of i is increment by 1 now value of i=2.
3.2 control jumps to while loop and test the condition while(i<=n)
i.e. while(2<=5) which results in true, statement inside body of loop fact=fact*i and i++ executes.
The value of fact=1 and i=2 the expression fact=fact*i evaluates fact=1*2 i.e. fact is assigned value 2.
fact=2
next i++ executes (i=i+1) and the vaue of i is increment by 1 now value of i=3.
3.3 control jumps to while loop and test the condition while(i<=n) i.e. while(3<=5) which results in true.
The statement inside body of loop fact=fact*i and i++ executes.
The value of fact=2 and i=3 the expression fact=fact*i evaluates fact=2*3 i.e. fact is assigned value 6. now fact=6
next i++ executes (i=i+1) and the vaue of i is increment by 1 now value of i=4.
This process continues while the value of i<=n i.e 5<=5
.
.
.
3.5 control jumps to while loop and test the condition while(i<=n)
i.e. while(5<=5) which results in true, statement inside body of loop fact=fact*i and i++ executes.
The value of fact=24 and i=5 the expression fact=fact*i evaluates fact=24*5
i.e. fact is assigned value 120. fact=120
next i++ executes (i=i+1) and the vaue of i is increment by 1 now value of i=6.
3.6 control jumps to while loop and test the condition while(i<=n)
i.e. while(6<=5) which results in False and control jumps out of while loop.
4. Executes the printf("\n Factorial of %d=%d",n,fact);
statement and shows output.
Factorial of 5=120.
and our program stops the Execution.