Loop in C

There are different kinds of loops are used in C:

Pre-test Loops:
——————————————-

//while Loop
while (c < 10) 
  c++;

//for Loop
for (c = 2; c <= 10; c += 2) 
  printf("\nValue: %d\n",c);

Note: if you want to use multiple statements in the loop you have to write statements within {}. i.e.
int i=1;
for (c = 2; c <= 10; c += 2) 
{
printf("Iteration: ",i);
i++;
printf("\nValue: %d\n",c);
}

Post-test Loop:
——————————————-

//do-while loop
do 
  c++; 
while (c < 10);

Breaking out of loops:
——————————————–

int i = 0;
while (true) 
{
  if (i == 5)
    break;
  i++;
} 

Continue to next iteration:
——————————————–

for (i = 0; i < 5; i++) 
{
  if (i < 4)
    continue;
  printf("%d",i);   // Only prints 4
} 

Add a Comment