What are Loops in C?

Loop is used to execute the block of code several times according to the condition given in the loop. It means it executes the same code multiple times so it saves code and also helps to traverse the elements of an array.

There are 3 types of loop –

  • while loop
  • do – while loop
  • for loop

1. while Loop –

While loop execute the code until condition is false.

while(condition){
//code
}

while loop
e.g.

#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
while( i <=20 ) {
printf ("%d " , i );
i++;
}
getch();
}

Output
20

2. do – while loop

It also executes the code until condition is false. In this at least once, code is executed whether condition is true or false but this is not the case with while. While loop is executed only when the condition is true.
Syntax

do{
//code
}while(condition);

e.g.

#include<stdio.h>
#include<conio.h>
void main()
{
int i = 20;
do{
printf ("%d " , i );
i++;
}
while( i < =20 );
getch();
}

Output
20
21

3. for Loop

It also executes the code until condition is false. In this three parameters are given that is

  • Initialization
  • Condition
  • Increment/Decrement

Syntax

for(initialization;condition;increment/decrement)
{
//code
}

It is used when number of iterations are known where while is used when number of iterations are not known.
e.g.

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
for( i = 20; i < 25; i++) {
printf ("%d " , i);
}
getch();
}

Output
20
21
22
23
24

Watch this Video on C Programming & Data Structure by Intellipaat:

Loop Control Statements:
These control statements change the execution of the loop from its normal execution. The loop control structures are –
1. break statement – It is used to end the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
2. continue statement – It skip some statements according to the given condition.
3. goto statement – It transfer control to the labeled statement.

Recommended Videos

Leave a Reply

Your email address will not be published. Required fields are marked *