Loops in C | Set 2

By | February 21, 2023

Loops are very useful when you want to perform a task repeatedly. Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

A loop consists of two parts, a body of a loop and a control statement. The purpose of the loop is to repeat the same code a number of times.

Types of Loop :

There are 3 types of Loop in C language, namely:

1. for loop
A for loop is a more efficient loop structure in ‘C’ programming. The general structure of for loop is as follows:

Syntax :

for (initial value; condition; incrementation or decrementation ) 
{
  statements;
}

Note that the initial value of the for loop is performed only once.

  1. It first evaluates the initialization code.
  2. Then it checks the condition expression.
  3. If it is true, it executes the for-loop body.
  4. Then it evaluate the increment/decrement condition and again follows from step 2.

When the condition expression becomes false, it exits the loop.

2. while loop
It tests the condition before executing the loop body. The basic format of while loop is as follows:

Syntax :

// variable initialization;
while(condition)
{
    // statements;
    // variable increment or decrement; 
}

3. do while loop
It is more like a while statement, except that it tests the condition at the end of the loop body. If post-test is required, use a do-while loop.

Syntax :

initialization expression;
do
{
   // statements

   update_expression;
} while (test_expression);

Loop Control Statements :

Loop control statements change execution from its normal sequence. These control statements may used to terminate or continue forcefully before normal end of loop.

  1. ‘break’ statement
    It terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

  2. ‘continue’ statement
    It is opposite of ‘break’ statement, It continue statement is used inside loops. It forces the next iteration of the loop to take place, skipping any code in between.

  3. ‘goto’ statement
    It transfers control to the labeled statement. It provides an unconditional jump from the ‘goto’ to a labeled statement in the same function.

Infinite Loop :

It is a piece of coding that lacks a functional exit so that it repeats indefinitely. A loop becomes an infinite loop (sometimes called an endless loop) if a condition never becomes false. It may because of increment or decrement parameter is not set properly or absent. Or may because of conditions are always true.

Example :

#include 
 
int main () {

   for( ; ; ) {
      printf("This this a infinite loop\n");
   }

   return 0;
}

So, this loop will not be terminate. You can terminate an infinite loop by pressing Ctrl + C keys.



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.