loop in C Language

Loop is also important in C language. Because a lot of work is done through the loop. The for example loop is used the most in the array. If we want to print a statement more than once, then we can use loop. And can print more than one statement.

We have been provided with 3 types of loops in C language.

  • while loop
  • do while loop
  • for loop

while loop

To run the body continuously until a requried condition is fullfill is called looping. it is used to perform looping operations. when the condition will become false the execution of loop will be stopped.

syntax:

while( )
{
// body part
}

Its body will execute until the given condition is true.

Example:

#include< stdio.h >
void main()
{
int 1;
while(i<=5)
{
printf("%d\n",i);
i++;
}
}

Output:

1
2
3
4
5

In this above program i is a variable while initialized with 1, condition goes to 5 and it is incremented by 1 so the output will 1 to 5.

do while loop

The do while loop is similar to a while loop, but instead of checking the condtion first,the statement is executed first. After that condition check is done but it id only first time.

syntax:

do
{
// body part
}
while( );

Its body will execute until the given condition is true.

Example:

#include< stdio.h >
void main()
{
int 1;
do
{
printf("%d\n",i);
i++;
}
while(i<=5);
}

Output:

1
2
3
4
5

In the above program i is a variable which is initialized with 1,condition goes to 5 and it is incremented by 1 so the output will be 1 to 5.

for loop

For loop is used a lot in C language. Because this loop is very easy. And it is defined in a single statement. Three conditions are used in this loop. First initialization, second condition and third increment, these three conditions are used. Now look at the example given below.

syntax:

for(initialization;condition;increment/decrement)
{
// body part
}
  • In for loop there are three part initialization , condition, increment/decrement.
  • Initialization part executes only once.
  • All the three part of for loop are optional.

Example:

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

Output:

1
2
3
4
5

In the above program i is a variable which is intialized with 1, condition goes to 5 and its incremented by 1 so the output will be 1 to 5.

nested loop in c language

A loop inside another loop called nested loop so one for loop inside another for loop is called nested loop and so on.

syntax:

for(..;..;)
{
for(..;..;)
{
//statement/ body part
}
//statement/ body part
}

Example: print all prime number between 1 to 100.

#include< stdio.h >
void main()
{
int i,j;
for(i=2;i<=100;i++)
{
int c=i,f=0;
for(j=2;j<=c-1;j++)
{
if(c%j==0)
f=1;
}
if(f==0)
printf("%d ",c);
}
}

Output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97