Loops in C


March 5, 2022, Learn eTutorial
1505

In this tutorial you will master all aspects of loops in C. C programming language supports loops in three unique ways using for loop, while loop, and do-while loop. Also, you will see how the infinite loop works in C. 

Many times we get some situations where a specific block of codes needs to be executed repeatedly. When we are calculating the factorial of a number say 7, the multiplication continues to happen with the next smaller number (6,5,4..) and the cycle continues until it reaches 1. It will be great if we can write a set of common code for multiplication only once and get it executed repeatedly until the desired value (here 1) is reached. This set of common codes which gets repeated are collectively called 'loop' in the programming language. 

The Key Benefit of using loops in programming are

  • Loops enable code reusability
  • Loops reduce code complexity and redundancy
  • Loops help to traverse over data structures like arrays, linked lists, etc very easily.

TYPES OF LOOPS IN C

Loops, in  C programming, is basically classified into three :

  1. for loop
  2. while loop 
  3. do-while loop

For loop in C:

The 'for' keyword in C language can make loop execution look simple and easy to understand. for loop is the frequently used loop in C programs which is also referred to as a pre-tested loop. This is because the condition is evaluated prior to the execution of the loop body. For loop is used in cases where the number of iterations is known beforehand.
The structure of for loop begins with the keyword ‘for’ followed by a parenthesis (), in which you have to write three things operated by a semicolon

i. initialization (i=1)
ii. condition (i<=5)
iii. increment (i=i+1 or ++i or i++)

 

Syntax of for loop

for (initialization; condition test; increment or decrement)
{
       //loop body contains statements to be executed
}

FLOWCHART OF FOR LOOP

FLOWCHART OF FOR LOOP

Step 1: The first and foremost step is initializing the counter variable.

Step 2: In the second step the condition is evaluated, where the counter variable is tested for the specified condition.

  • if the condition returns true then the codes inside the body of for loop get executed.
  • if the condition returns false then the for loop gets terminated and the control exits the loop.

Step 3: In the final step the counter variable is either incremented or decremented, depending on the operation (++ or - -).


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

}

Output:

1
4
9
16
25
36
49
64
81
100

This example can be explained as follows.

Step 1: Initially the counter variable i is initialized with value 1.
Step 2: Condition i <= 10 is evaluated, i.e, 1 less than or equal to 10 is checked and the condition returns true. 
Step 3: Control shift to statement inside the loop which is to print (i*i), means 1*1. Result 1 is printed.
Step 4: the counter variable value is incremented to 2 as the operation is i++ and repeats the steps till the condition fails. i.e. when the value of the counter variable reaches 11 it will terminate the loop and exit from the loop.

LOOP BODY 

The statements enclosed within braces{} constitute the body of the for loop(loop body). If the loop contains only one statement then there is no necessity to encase them in braces. The braces determine the scope of the body and hence is known as block separator. The life is a variable declared inside the for loop is confined to that loop only and not outside.

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

}

Output:

1 , 5
2 , 5
3 , 5
4 , 5
5 , 5
6 , 5
7 , 5
8 , 5
9 , 5
10 , 5

Nested for Loop in C

C language also supports the nesting of ‘for loops’. Loops inside a loop are generally known as nested loops. Nesting can be done to any level but keeping it simple and complex free is better while scripting. Nested for loops are usually used to represent two-dimensional arrays.

Syntax of Nested for loop

for (initialization; condition; increment/decrement)   
{  
    for(initialization; condition; increment/decrement)  
    {  
           // body of inner loop.  
    }  
    // body of outer loop.  
}  

See below simple code fragment shows how to print multiplication table using nested for loops.

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

}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10

While loop in C

Another type of loop available in C is the while loop. Like for loop, while loop is also known as a pre-tested loop because prior to execution conditions are checked. While loop is normally used when we don’t know the number of iterations beforehand.

Syntax of while loop

while(condition){  
//body of while loop 
}  

In this loop architecture 'while' is followed by a condition and if it is satisfied, the execution of the loop starts. After the execution of each cycle, the compiler will check whether the condition under while is still met or not. If it does the loop will execute again and again, otherwise not.

FLOWCHART OF WHILE LOOP

FLOWCHART OF WHILE LOOP

While loop example

Let’s see how we changed the previous example of printing the squares of numbers.

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

}

Output:

1
4
9
16
25
36
49
64
81
100

Note that we have given 'i' an initial value of 1. In the first cycle 'while' checks whether it is lesser or equal to 10 or not. As 1<10, the codes execute and print the square of 1 as 1. The statement 'i=i+1' increases the value of 'i' from 1 to 2. Now 'while' checks again and finds 2<10, consequently prints the square of 2 which is 4. Similarly, 3,4,....till 10 is printed. But at the last statement of the last loop 'i' becomes 11'. So 'while' finds 11 to be neither less than nor equal to 10 and the loop terminates.

Nested While Loop

Like for loop, we can also nest a while loop inside another while loop. 

Syntax of Nested while loop

while(condition)  
{  
    while(condition)  
    {  
         // body of the inner loop.  
    }  
// body of outer loop.  

Nested while loop example

See the below example to print the multiplication table using nested while loop.

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

}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10

do..while Loop in C

Another type of loop in C language is the do-while loop which is similar to while with one exception that the condition evaluation takes place only after the execution of the statements inside the body of  do-while. Hence do-while loop is also known as the post-condition loop. The do-while loop is mostly used in places where we need to execute the statements inside the body at least once like menu-driven programs.

To understand it clearly, let's consider the case of a TV remote where you have multiple choices(menu-driven) to watch TV: If you want to surf through channels on your TV t you have to watch at least 1 channel, and when you reach a condition of boredom you can surf to other channels. 

Syntax of do..while loop

do{  
//body of do-while loop   
} while(condition);  
 
  • In the case of this loop, firstly initialization of the value happens.
  • Then the keyword 'do' is followed by braces {} in which statement and increment are written.
  • Immediately after this, the condition to be evaluated is written after the keyword 'while'.

do..while loop example

See below codes illustrating an example of a do-while loop.

#include<stdio.h>
#include
void main()
{
int channel,cursor;
    char c;
    do{
    printf("\n1.TLC\n2.CNN\n3.GEO\n4.Exit\n");
    scanf("%d",&choice);
    switch(channel)
    {
        case 1 :
        printf("I am Watching TLC\n");
        break;
        case 2:
        printf("I am watching CNN\n");
        break;
        case 3:
        printf("I am watching GEO\n");
        break;
        case 4:
        exit(0);
        break;
        default:
        printf("Watching default channel - BBC");
    }
    printf(" \n Do you want to surf another channel?");
    scanf("%d",&cursor);
    scanf("%c",&c);
    }while(c=='y');
}

Output:

1.TLC
2.CNN
3.GEO
4.Exit
2
I am watching CNN

Do you want to surf another channel?y

1.TLC
2.CNN
3.GEO
4.Exit
1
I am Watching TLC

Do you want to surf another channel?n

Nested do..while loop

Like the other two loops, the do-while loop also supports nesting

Syntax of Nested do...while loop

do  
{  
   do  
  {   
      //  body of inner do-while loop.  
   } while(condition);  
   //  body of outer do-while loop.   
} while(condition); 
 

Nested do..while example

See the below example to print the multiplication table using a nested do-while loop.

#include<stdio.h>
void main()
{
   int i =1;
 int j=1;
 do
 {
     do
     {

         printf("%d x %d = %d\n",i ,j,(i*j));
         j=j+1;
     }while(j<=10);
     i=i+1;
 }while(i<2);
}

Output:

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
1 x 6 = 6
1 x 7 = 7
1 x 8 = 8
1 x 9 = 9
1 x 10 = 10

Infinite loop in C

An infinite loop, in the C language, is a loop construct that executes forever without terminating the loop. This type of loop produces an indefinite number of outputs, it is also named an indefinite loop or endless loop.

Use of Infinite loop:

Infinite loops are useful in situations where the user needs the application to execute indefinitely until the user needs to exit the application manually. Daily life applications which use infinite loops are all Operating systems, all servers, and games. All these applications work continuously until the user shuts down or exits. We can define infinite loop using all the three loops, for loop, while loop, or do-while loop. Also, goto statements which you will learn in the next tutorial can be used to create infinite loops.

Infinite loop example:

 Here is a simple example:


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

}

for (i=1;i++)

Here the value of I will change like 1,2,3.... But will never be less than '0' resulting in an infinite loop.The output will be like:

infinite loop output