Write a program to find the Factorial of a number using 'While-Loop' :-


//Factorial of a number using 'While-Loop'

#include<stdio.h>
#include<conio.h>
void main()
{
int n,fact=1;

printf("Enter any number:");
scanf("%d",&n);

while(n!=0)
{
fact=fact*n;
n--;
}
printf("Factorial of a number is:%d",fact);
getch();
}

Output:


Enter any number:5
Factorial of a number is:120

			

Working:-

1. First the computer reads the number to find the factorial of the number from the user.
2. Then using while loop the value of ‘i’ is multiplied with the value of ‘f’.
3. The loop continues till the value of ‘i’ is less than or equal to ‘n’.
4. Finally the factorial value of the given number is printed.

Previous Next


NOTE:- You can put this program inside some function if you want. And you can also design it in such a way that if the user inputs a number less than zero, you can ask him to enter the input again. This can be done by putting scanf statement inside a while loop and checking for the ‘not less than zero’ condition inside. And if condition holds we can break the loop to proceed further. You try it!