What is Loop in C? Describe Different Types of Loop with Examples

What is Loop in C?


In computer programming, a loop is a sequence of instruction that is continually repeated until a certain condition is reached. It means when a programmer writes a loop program, they set some condition to check the program correctly work or not. The certain process is to continue until the counter has reached the program condition.


Iterative Statement:

This statement is used to repeat the execution of a list of the statement. Depending on the value of an integer expression.'C' languages support three types of the iterative statement also known as looping statement.

  1. For Loop
  2. While Loop
  3. Do-while Loop


For Loop:

for loop is a repetition control structure that allows you to efficiently write a loop program that needs to execute a specific number of times.



Syntax of For Loop in C Programming Languages:

for(Initialization; Condition; Increment/Decrement)
{
statement(s);
}



Examples of For Loop Program:

Write a C Program to Print First 10 Integer Number Using For Loop.

#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=1; i<=10; i++)
{
printf("%d\n",i);
}
getch();
}







While Loop:
It is a type of entry control loop. It means when you run a while loop program, the program first checks the condition. If the condition is ok, the program works on the statement process, otherwise the program exit.


Syntax of While Loop in C Programming Languages:

Initialization;                         int i=1;
while(condition)                     while(i<=10)
{                                          {
statement;                             printf("%d",i);
Increment/Decrement              i++;
}                                           }




Examples of While Loop Program in C:
Write a C program to print 1 to 10 number summation result using While Loop.

#include<stdio.h>
#include<conio.h>
main()
{
int i=1;sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
printf("\n%d",sum);
getch();
}






Do-While Loop:
The do-while loop is similar to the while loop. The only difference is that in a do-while loop, the test condition is tested at the end of the loop. The do-while loop also known as an exit control loop.



Syntax of Do-while loop in a C Program:

Initialization;
Do
{
statement;
increment/decrement
}while(condition);





Examples of Do-While Loop Program in C:
Write a C program to Calculate the Factorial of a Number using Do-while loop.

#include<stdio.h>
#include<conio.h>
main()
{
int n, fact=1;
printf("Enter a Number");
scanf("%d",&n);
do{
fact=fact*n;
n--;
}while(n>=1);
printf("The factorial of a number%d",fact);
getch();
}

Post a Comment

0 Comments