{{announcement.body}}
{{announcement.title}}

Types of Loops in C and C++?

DZone 's Guide to

Types of Loops in C and C++?

In this in-depth article, learn about the types of loops in C and C++.

· IoT Zone ·
Free Resource

Loops in a programming language is a piece of code that get executed repeatedly until the specified condition becomes false. A loop consists of two parts, a block of statements and a condition that control the loop.

Loops mainly consisted of three statements – initialization condition, test condition, update condition.

For example, if we want to print “Hello Codies” 5 times, we can do this in two ways. Writing the statement 5 times (#1) or use loops which save time and effort (#2).

Java
 




xxxxxxxxxx
1
13


 
1
#1
2
 
          
3
#include <stdio.h> 
4
int main() 
5
{ 
6
     printf("Hello Codies\n"); 
7
     printf("Hello Codies\n");
8
     printf("Hello Codies\n");
9
     printf("Hello Codies\n");
10
     printf("Hello Codies\n");
11
        
12
    return 0; 
13
}


Java
 




xxxxxxxxxx
1
16


 
1
#2
2
 
          
3
#include <stdio.h> 
4
  
5
int main() 
6
{ 
7
  int i; 
8
  
9
    // Writing a for loop 
10
    // to print Hello Codies 5 times 
11
   
12
    for (i = 1; i <= 5; i++) { 
13
        printf("Hello Codies\n"); 
14
    } 
15
    return 0; 
16
}



Output:

Java
 




xxxxxxxxxx
1


 
1
Hello Codies
2
Hello Codies
3
Hello Codies
4
Hello Codies
5
Hello Codies



In this tutorial, you will learn-

  1. Types of Loops
  2. While Loop
  3. Do-While loop
  4. For loop
  5. Nested loop
  6. Break Statement
  7. Continue Statement

Types of Loops in C/C++

Loops are classified into two types depending upon the position control statements:

  • Entry controlled loop
  • Exit controlled loop

Entry controlled loop: A conditional statement is evaluated before executing the body of a loop. It is also called as a pre-checking or Counter controlled loops where the programmer already know how many times the loop get executed. Counter controlled loops are often called definite iteration because the number of repetitions is known before the loop begins execution.

Exit controlled loop: In this type of loops conditional statement are evaluated after executing the loop body once irrespective of whether the test condition is true or false. It is also called as a post-checking or Sentinel controlled Loop because the programmer don’t know exactly know how many times loop will be executed. Sentinel-controlled loop also known as indefinite repetition.

The control conditions must be specified properly otherwise the loop will execute infinite number of times (infinite loop). An infinite loop occurs when no termination condition is specified or specified conditions never meet.

C programming language provides us with 3 types of loop and C++ has 4th extra loop:

  • while loop
  • do-while loop
  • for loop
  • Nested Loop (only in C++)

The syntax of these loops mainly differs in the placement of these three statements initialization condition, test condition, update condition.

While Loop in C/C++

The while loop specify that a program should repeat set of instruction inside the block till the condition remains true. While loop used in place where we don’t know number of iteration before and it depends on the update inside the block. While loop is Entry Controlled loop and widely used in C/C++.

Syntax of WHILE Loop:

Java
 




xxxxxxxxxx
1


 
1
initialization condition;
2
while (test_ condition)
3
{
4
   // statements
5
 
6
  update_ condition;
7
}



Flow Chart of While loop.

In While loop, condition evaluated first if condition is TRUE than block of statements get executed and update condition then control again goes back at the beginning, and the condition is checked again if it is true, the same process is executed until the given condition becomes false. Once the test condition results FALSE control goes back to main program. While Loop is Entry-Controlled Loop.

Note: If Loop contains only one statement, then the curly braces are not compulsory. Though It is a good practice to include braces.

Following program illustrates a while loop:

Java
 




xxxxxxxxxx
1
13


 
1
#include<stdio.h>
2
 
          
3
int main()
4
{
5
  int num=1;    //initializing the variable
6
    
7
     while(num<=5)            //while loop with test condition
8
    {
9
       printf("%d ",num);  
10
       num++;        //incrementing (update condition)
11
    }
12
    return 0;
13
}



Output:

Java
 




xxxxxxxxxx
1


 
1
1 2 3 4 5



The above program prints series of numbers from 1 to 5 using a while loop.

Let’s see what happening in above program step by step.

Step 1: We have initialized variable ‘num = 1’.

Step 2: In while condition we are evaluating is ‘num’ value is less than or equal to 5, if ‘num’ becomes greater than 5 than this condition become False.

Step 3: For now ‘num = 1’, we enter the loop comparing 1 <= 5 which result true so the body of loop i.e. ‘num’ value 1 got printed.

Step 4: In this step ‘num’ value increased by 1 i.e now ‘num = 2’.

Now step 3 get repeated again with ‘num = 2’ and print the ‘num’ value 2, similarly 3,4,5. When ‘num’ got increase to 6 (num =6) while condition become FALSE & loop terminated than control goes back to main() function as there is nothing after loop do program exits with returning 0 indicating that everything went well.

Do-While Loop in C/C++

Do-while loop is almost similar to the while loop except that the body of a loop executed once before test condition is evaluated. It is an Exit-controlled loop.

The basic syntax of do-while loop is as follows:

Java
 




xxxxxxxxxx
1


 
1
do {
2
  statements
3
} while (test condition); 



Flow Chart of Do – While loop.

Do–while loop used in cases where we have to execute a body of the loop at least once irrespective of the condition. Unlike while loop, In do-while loop the body of a loop is always executed at least once then checks the condition. If the condition is true, then it will again execute the body of a loop else if condition becomes FALSE control goes out of the loop to main program.

Following program illustrates the do-while loop:

Java
 




xxxxxxxxxx
1
16


 
1
#include<stdio.h>
2
 
          
3
int main() 
4
{ 
5
  int num=6;    //initializing the variable
6
    
7
      do    
8
    {
9
        printf("%d\n",num);
10
        num++;        //incrementing (update condition)
11
 
          
12
    }while(num<=5); //while loop with test condition
13
 
          
14
  
15
    return 0; 
16
} 



Output:

Java
 




xxxxxxxxxx
1


 
1
6



In the above program, we have initialized ‘num = 6’ and printed the ‘num =6’ without involving while condition which will result in FALSE as 6 > 5. After printing 6 we compared which turned out to be FALSE thus terminating the loop.

Important NOTE about while and Do-while loop:

We can use multiple test condition in both While and Do-while loop using binary operators, follow below program.

Multiple test conditions using binary operators in while loop.

Java
 




xxxxxxxxxx
1
14


 
1
#include <stdio.h> 
2
  
3
int main()
4
{
5
   int num=1;    //initializing the variable
6
    
7
           while(num<=5 && num!=3)    //while loop with multiple test condition
8
          {
9
    printf("%d ",num);
10
    num++;        //incrementing (update condition)
11
    }
12
    
13
return 0;
14
}



Output:

Java
 




xxxxxxxxxx
1


 
1
1 2



Here the while loop body executed only if number is less than equal to 5 and less than 3. To manually compile you need to know Truth table.

Truth Table

Manually compiling above program.

Java
 




xxxxxxxxxx
1
15


 
1
num = 1
2
 
          
3
num < = 5 (true i.e. 1) and num < 3 (true i.e. 1)
4
 
          
5
1 & 1 = 1(which is true, so the loop executed)
6
1 got printed (num increased by 1, num=2)
7
Similarly, 2 got printed (num increased by 1, num=3)
8
 
          
9
 
          
10
But when  
11
num = 3
12
 
          
13
num < = 5 (true i.e. 1) and num < 3 (False i.e. 0)
14
 
          
15
1 & 0 = 0 (Which is False, so loop terminated) 



Multiple test conditions in Do-While loop.

Java
 




xxxxxxxxxx
1
15


 
1
#include <stdio.h> 
2
  
3
int main() 
4
{ 
5
int num=6;    //initializing the variable
6
    do    
7
    {
8
         printf("%d ",num);
9
         num--;        //decrementing (update condition)
10
 
          
11
    }while(num<=5 && num > 0); //while loop with test condition
12
 
          
13
  
14
    return 0; 
15
}



Output:

Java
 




xxxxxxxxxx
1


 
1
6 5 4 3 2 1



Here the loop body executed once irrespective of condition than ‘num’ value decreased & compared with while condition. Loop gets terminated only if either one or both the conditions become. To manually compile you need to know Truth table.

Java
 




xxxxxxxxxx
1
20


 
1
num = 6 ( 6 got printed irrespective of while condition)
2
 
          
3
num = 5 (decremented after printing 6)
4
 
          
5
num < = 5 (true i.e. 1) and num > 0 (true i.e. 1)
6
 
          
7
1 & 1 = 1(which is true, so the loop executed)
8
5 printed (num decreased by 1, num=4)
9
Similarly, 4 got printed (num decreased by 1, num=3)
10
Similarly, 3 got printed (num decreased by 1, num=2)
11
Similarly, 2 got printed (num decreased by 1, num=1)
12
Similarly, 1 got printed (num decreased by 1, num=0)
13
 
          
14
 
          
15
When
16
num = 0
17
 
          
18
num < = 5 (true i.e. 1) and num > 0 (False i.e. 0)
19
 
          
20
1 & 0 = 0 (Which is False, so loop terminated) 



For Loop in C/C++

A for loop is a more efficient loop structure in C/C++ programming. A for loop is a repetition control structure which allows us to execute piece of code a specific number of times. The general syntax of for loop is as follows:

Java
 




xxxxxxxxxx
1


 
1
for (initial value; condition; increment or decrement) 
2
{
3
  statements;
4
}



Flow Chart of FOR loop.

  • The variable assigned initial value only once in for loop.
  • The condition is a Boolean expression that tests and compares the counter (initialized value) for a fixed iteration and stops the for loop when the condition is false.
  • The increment/decrement increases (or decreases) the counter by a set value.

Following program illustrates the use of FOR loop:

Java
 




xxxxxxxxxx
1
11


 
1
#include<stdio.h>
2
int main()
3
{
4
   int i;
5
    
6
       for(i=0;i<=10;i++)    //for loop to print 0-10 numbers
7
       {
8
      printf("%d ",i);    //to print the number
9
    }
10
    return 0;
11
}



Output:

Java
 




xxxxxxxxxx
1


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



The above program prints the number series from 0-10 using FOR loop.

Step 1. Declared a variable i of int data type to store values.

Step 2. In loop, we have initialized variable i = 1, than the condition part and the increment part.

Step 3. In loop body, we have a print function to print the value of variable i on a new line in the console. After printing i = 1, the value of i will be incremented, and it will become 2. Now the variable has the value 2. The condition will be evaluated again and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 0-10 will be printed on the screen.

In C/C++, the for loop can have multiple condition separated by commas in each part.

For example:

Java
 




xxxxxxxxxx
1
11


 
1
#include<stdio.h>
2
int main()
3
{
4
   int i;
5
    
6
       for(i=0;i>5,i<=10;i++)    //for loop to print 0-10 numbers
7
       {
8
      printf("%d ",i);    //to print the number
9
    }
10
    return 0;
11
}



Output:

Java
 




xxxxxxxxxx
1


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



Above loop compile without any error, but the twist is the output will be 0-10 because 2nd condition is considered 1st condition is just evaluated and kept aside, whole loop executed on the basis of 2nd condition.

Now, if we you want to test both conditions, use the && operator.

Java
 




xxxxxxxxxx
1
11


 
1
#include<stdio.h>
2
int main()
3
{
4
   int i;
5
    
6
       for(i=6;i>5 && i<10;i++)    //for loop to print 6-9 numbers
7
       {
8
      printf("%d ",i);    //to print the number
9
    }
10
    return 0;
11
}



Output:

Java
 




xxxxxxxxxx
1


 
1
6 7 8 9



And in FOR loop, we can skip the initial value assignment, condition and/or increment by adding a semicolon.

For example:

Java
 




xxxxxxxxxx
1
23


 
1
#1 //Skip initialization 
2
i=1
3
for(;i<5;i++) { 
4
  statements; 
5
}
6
 
          
7
#2 //skip whole for loop statement
8
 
          
9
int main()
10
{
11
 int i=1;
12
 
          
13
for(;;)    //for loop to print 1-4 numbers
14
{
15
     if(i<5){
16
    printf("%d ",i);
17
        
18
    i++;}
19
else
20
    break; //terminate loop when i>=5
21
    }
22
    return 0;
23
} 



Nested Loops

Nested loops mean loop inside other loop for each iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example printing a multiplication table:

Java
 




xxxxxxxxxx
1
12


 
1
#include <stdio.h>
2
int main() {
3
int i, j;
4
 
          
5
for (i = 1; i <= 3; i++) { // outer loop
6
  for (j = 1; j <= 5; j++) { // inner loop
7
    printf("%d x %d = %d\n", i, j, i*j);
8
  }
9
  printf("\n"); /* blank line between tables */
10
}
11
return 0;
12
}



Output:

Java
 




xxxxxxxxxx
1
17


 
1
1 x 1 = 1
2
1 x 2 = 2
3
1 x 3 = 3
4
1 x 4 = 4
5
1 x 5 = 5
6
 
          
7
2 x 1 = 2
8
2 x 2 = 4
9
2 x 3 = 6
10
2 x 4 = 8
11
2 x 5 = 10
12
 
          
13
3 x 1 = 3
14
3 x 2 = 6
15
3 x 3 = 9
16
3 x 4 = 12
17
3 x 5 = 15



Break Statement

The break in C/C++ is a loop control statement mainly in the switch statement to jump out of switch block after the desired case is met. BREAK also used to terminate the loop when encountered from within a loop, the loop iterations stops and control returns from the loop immediately to the first statement after the loop.

Syntax:

Java
 




xxxxxxxxxx
1


 
1
break; 



Basically break statements are used in the situations where the actual number of iterations not known or we want to terminate the loop based on some condition.

Java
 




xxxxxxxxxx
1
14


 
1
#include <stdio.h>
2
 
          
3
int main() {
4
int n = 5;
5
 
          
6
while (n > 0) {
7
  if (n == 3)
8
    break;
9
  printf("%d ", n);
10
  n--;
11
}
12
 
          
13
return 0;
14
}



Output:

Java
 




xxxxxxxxxx
1


 
1
5 4



Continue Statement

Continue statement is similar to BREAK statement in opposite way, whenever continue statement encountered instead of terminating the loop, it forces loop to execute the next iteration and skips the current iteration in loop.

For example:

Java
 




xxxxxxxxxx
1
11


 
1
#include <stdio.h>
2
int main() {
3
int n = 0;
4
while (n < 10) {
5
  n++;
6
  if (n == 5)
7
    continue;
8
 printf("%d ", n); 
9
}
10
    return 0;
11
}



Output:

Java
 




xxxxxxxxxx
1


 
1
1 2 3 4 6 7 8 9 10



So, the value 5 is skipped.

Explanation

Consider the above situation where you need to write a program which prints number from 10 to 0 and but not 5. What we did here is we run a loop from 10 to 0 and every time we have to compare the value of iterator ‘n’ with 5. If n equal to 5 than the continue statement executed to force loop continue to next iteration without printing 5.

Please comment if you find anything incorrect or any error.

Topics:
c, c++, c++ beginner course, iot, learn c++, tutorial

Published at DZone with permission of Chand Pasha . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}