Loops in C

Loops in C: Loops are nothing but, if you want to execute a block of code specified number of times until a condition is met. Every programming has the feature to instruct to do such repetitive tasks. Programming languages provide various control structures that allow for more complicated execution paths.

loops in c

There are different types of loops available in C language.

  1. C for loop
  2. C While loop
  3. C  Do-while loop

Loops in C

1) C For loop

In for loop, the loop will be executed until the condition becomes false.

Syntax

for(init; condition; increment)
{
statement(s);  }

Flow Chart

for loop in C

Flow of for loop

  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables.
  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’ loop.
  • After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables.
  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself. After the condition becomes false, the ‘for’ loop terminates.

Example

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

2) C While loop

In while loop control statement loop will be executed until the condition becomes false. The statement(s) may be a single statement or a block of statements. And the condition may be any expression, and true is any nonzero value. And loop iterates while the condition is true. When the condition becomes false, the program control passes to the line immediately following the loop.

Syntax

while(condition)  { 
statement(s); } 

Flow Chart

while loop in C

Example

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

Output: 3 4 5 6 7 8 9

3) Do While loop in C

While loop is executed irrespective of the condition for the first time. Then, the 2nd time onwards loop is executed until the condition becomes false. A do…while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Syntax

do  { 
statement(s);  
} while( condition ); 

Flow Chart

Do-While Loop in C

 

Example

#include<stdio.h>                  
int main()  {                     
int i=1;                        
do {                           
printf("Value of i is %d\n",i);                     
i++;                    
} 
while(i<=4 && i>=2);                   
}

Output
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4