Loop Constructs In C++ With Examples

An In-Depth Look At Loops In C++ Along With Its Types.

In addition to Decision-making Constructs that we have seen in our last tutorial, there may arise some situations wherein we have to execute a block of statement repeatedly.

Such a situation requires that we have a condition that checks if the block of code should be executed or not. This is done by loop constructs in programming. C++ also has various loop constructs that allow us to execute a block of code repeatedly or until a condition is true. In this tutorial, we will explore these loop constructs in C++ in detail.

Suggested Read => C++ Training Guide For All

LOOP CONSTRUCTS IN C++1

Loops In C++

For Loop

The construct that executes statements repetitively is the “for” loop.

The general syntax of for loop is:

for(initialization; condition; increment)
 {
                  Statement block;
 }

The general syntax of for loop shows that it consists of three parts. The initialization expression consists of the initial values set for the loop variable. The condition expression provides the condition that is checked to exit the loop. The increment part is used to increment the loop variable after every iteration.

Initially, the “for” loop begins execution with initialization of the loop variable. Then it tests the condition. If the value of the loop variable satisfies the condition, then it executes the statement block.

When statement block is executed, the loop variable is incremented as per the increment specified and the next iteration is started. This way, the loop completes the iterations until the condition is fulfilled. Then the “for” loop is exited.

This is the flow diagram for the “for” loop construct.

flow diagram of “for” loop construct

Let us see an example of “for” loop in C++ below.

#include <iostream>
#include <string>
using namespace std;

int main()
 {
  cout<<"Printing 2's multiples less than 20"<<endl;
  for(int i =2;i<=20;i +=2)
   {cout<<"i = "<<i<<"\t";
   }
 }

Output:

Printing 2's multiples less than 20
i = 2 i = 4 i = 6 i = 8 i = 10 i = 12 i = 14 i = 16 i = 18 i = 20

Here we print the 2’s multiples up to 20 using a “for” loop. Note that it is convenient to use when we know the number of iterations beforehand.

While Loop

C++ provides yet another loop construct that allows us to execute a set of statements in a repetitive manner. This is ‘while’ loop.

The general syntax of ‘while’ loop is:

 while(condition)
 {
   Statement_block;
 }

A ‘while’ loop repeats a set of the statement as long as the condition is true. So before the start of every iteration, the condition is evaluated. If it is fulfilled, statement_block is inside while loop. Otherwise, the loop is exited.

Below given is the flow diagram of “while” loop.

flow diagram of “while” loop

Given below is an example program to demonstrate while loop:

#include <iostream>
#include <string>
using namespace std;

int main()
 {
  cout<<"Printing 2's multiples less than 20"<<endl;
  int i=2;
  while(i<=20)
  {
      cout<<"i = "<<i<<"\t";
      i += 2;
  }
 }

Output:

Printing 2's multiples less than 20
i = 2 i = 4 i = 6 i = 8 i = 10 i = 12 i = 14 i = 16 i = 18 i = 20

To simplify the concept, we have modified the same program that was used to demonstrate the “for” loop. Here unlike for loop, we specify the initial value of the loop variable outside the while loop. Then we begin the while loop where we specify the condition.

Inside the loop, we increment the loop variable. The code inside the “while” loop is executed as long as the condition is satisfied.

When we are not sure about the exact number of iterations that the code will be executed for, we go for “while” loop.

Do While Loop

The next loop in C++ is the “do-while” loop. In the case of “while” loop, we check the condition first and then execute the iteration. In the case of “do-while” loop, we execute the iteration first and then we evaluate the condition in order to continue with the loop.

The general syntax of the “do-while” loop is:

do{
…
…
}while(condition);

The flow diagram of Do While Loop:

flow diagram of “DO while” loop.

As shown in the flow diagram, the ‘do-while’ loop begins with the statement block. It is executed first and then the condition is checked. If the condition is true, then the statement block is repeatedly executed until the condition becomes false.

Let us understand this with the help of an Example.

#include <iostream>
#include <string>
using namespace std;

int main()
 {
   cout<<"Printing 2's multiples less than 20"<<endl;
   int i=2;
   do
   {
   cout<<"i = "<<i<<"\t";
     i += 2;
   }while(i<=20);
 }

Output:

Printing 2's multiples less than 20
i = 2 i = 4 i = 6 i = 8 i = 10 i = 12 i = 14 i = 16 i = 18 i = 20

We have modified the same example as the previous loops. Note that the condition is checked at the end after the statement block is executed. This ensures that the loop is executed at least once before exiting.

Break And Continue Statements

Whenever we need to exit out of the loop/statement block without completing it or if we have to skip iteration, then we make use of two special statements i.e. break and continue.

The “break” statement of C++ is used to break and exit out of the loop or the statement block. The “break” statement immediately terminates the loop or the statement block the moment it is encountered.

This is required when we abruptly want to exit from a particular construct irrespective of the test condition.

Similarly, if we want to skip a particular statement or jump to the next iteration without completing the current iteration, then we use the “continue” statement. In other words, “continue” is used to continue the flow of the program to the next step.

Given below is the flow diagram of Break and Continue statements

Break

Flow diagram of Break Statement

Continue

Flow diagram of Continue Statement

Let us see an example of using the break and continue statements in the code.

#include <iostream>
#include <string>
using namespace std;

int main()
 {
   cout<<"Printing 2's multiples less than 20"<<endl;
   int i =0;
   while(1)
   {
     if(i==0){
     i += 2;
     continue;}
     cout<<"i = "<<i<<"\t"; i += 2; if(i > 20) break;
   }
 }

Output:

Printing 2's multiples less than 20
i = 2 i = 4 i = 6 i = 8 i = 10 i = 12 i = 14 i = 16 i = 18 i = 20

Once again we have taken the same example of printing 2’s multiples up to 20. In this case, we have initialized the loop variable to zero. Then we use an infinite while loop and inside the loop, we skip the first iteration using the continue statement.

Next, we use the break statement to exit out of the loop the moment the loop variable becomes greater than 20.

Yet another situation where we use the break statement is in the case of the switch statement. We have already seen the switch statement.

When the expression matches any case of the switch statement, the code for that particular is executed and then the control passes to the cases following the matched case. This way, after matching the case, all subsequent cases are also executed before exiting the switch statement. This results in the erroneous output.

In order to prevent the subsequent cases from executing, we introduce the break statement at the end of each case. This makes the controlled exit out of the switch statement once the matching case is found and code is executed.

Infinite Loop

An infinite loop is also called an endless loop. An infinite loop occurs when the loop condition always evaluates to true. As a result, it executes indefinitely.

For Example for(;;) will result in an infinite “for” loop.

While(;) or while(1) will result in while loop being executed indefinitely.

Infinite loops should not be encouraged in programming but if at all the need arises, we should be able to break out of the loop using a terminating condition inside the loop.

Infinite loops result in an error. We should be cautious while using the loop constructs in C++.

  1. ‘For' loops should be used when we know the number of iterations beforehand.
  2. While loop should be used when we know the terminating condition of the loop.
  3. The do-while loop should be used when we want the loop to be executed at least once.

Conclusion

With this, we conclude this tutorial on loops in C++.

In our next tutorials, we will discuss arrays and strings in detail followed by functions in C++.

=> Visit Here For The Complete C++ Tutorials List.