Practical no.
04
Aim: Write a Program in “C” to find factorial of no using looping statement
(for, while & do-while)
Objective: Learning Array concept
Theory :
for Loop
When you know exactly how many times you want to loop through a block of code, use the for loop .
Syntax
for (expression 1; expression 2; expression 3)
{
// code block to be executed
}
Programm:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,fact=1,number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}
Output:
Enter a number
5
Factorial of 5 is 120
While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
Programm:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,fact=1,number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
while(i<=number)
{
fact=fact*i;
i++;
}
printf("Factorial of %d is: %d",number,fact);
getch();
}
Output:
Enter a number
5
Factorial of 5 is 120
Do-while Loop
The do-while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as
the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Programm:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1,fact=1,number;
clrscr();
printf("Enter a number: ");
scanf("%d",&number);
do
{
fact=fact*i;
i++;
}
While(i<=number);
printf("Factorial of %d is: %d",number,fact);
getch();
}
Output:
Enter a number
5
Factorial of 5 is 120
Conclusion : we have execute for while and do-while loop.