Loops in C programming language

The loop in C program execute a block of codes for multiple times until a specific condition is achieved. There are three types of loops used in the C language.
  • while loop
  • do while loop
  • for loop

while loop : A while loop in C program repeatedly executes a target statement as long as a given condition is true. The condition of the loop is tested before the body of the loop is executed, hence it is called an entry-controlled loop.

The syntax of a while loop in C programming language is :
while(condition)
{
      statement(s);
}

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

Output :
1
2
3
4
5


do while loop : The do...while loop is similar to the while loop with one important difference. The body of do...while loop is executed once, before checking the condition. Hence, the do...while loop is executed at least once.

The syntax of a do...while loop in C programming language is :
do{
      code to be executed;
}while(condition);

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

Output :
1
2
3
4
5


for loop : The for loop in C program is used to iterate the statements or a part of the program several times.

The syntax of a for loop in C programming language is :
for ( initialization; condition; increment )
{
      statement(s);
}

Note :

(i) The initialization statement is executed only once.
(2) Then, the condition is evaluated. If the condition is evaluated to false, the for loop is terminated. However, if the condition is evaluated to true, statements inside the body of for loop are executed.
(3) After successful execution of statements inside the body of loop, the counter variable is incremented or decremented, depending on the operation (++ or --).

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

Output :
1
2
3
4
5

0 Comments