Loop in C++

Video Tutorial
FREE
Loops Intro thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate

Overview

Loops are used in computer programming to execute a group of instructions or a block of code multiple times without writing the same block of code repeatedly. There are mainly two types of loops: entry controlled loop and exit controlled loop. for loop and while loop is considered as entry controlled loop and do-while loop is considered as exit controlled loop.

Need for Loop in C++

Loops in C++ are essential for repetitive or iterative tasks, where you want to execute a block of code multiple times without writing the same code over and over. They simplify the process of performing repetitive operations. Let's illustrate this with an example:

Example - Printing "Hello" Five Times Using a Loop:

Without a loop, you would have to write the "Hello" statement five times, like this:

Now, let's see how to achieve the same result using a loop, in this case, a for loop:

In this version, we use a for loop to iterate from 0 to 4 (a total of five times), and inside the loop, we print "Hello" using the std::cout statement. This approach is more efficient and maintains code simplicity, especially when you need to repeat an action a large number of times. Loops in C++ are invaluable for automating such repetitive tasks.

Types of Loops in C++

Based on when the condition is checked in the loop, We have two types of loops.

  • Entry Controlled loops
  • Exit Controlled Loops

Entry Controlled Loops in C++

If the condition is checked before entering the body of the loop, then it is known as Entry controlled loop. The block of code present in the body of the loop is executed only if the condition is true.

Example: For loop and While loop.

Exit Controlled Loops in C++

If the condition is checked after executing the block of code in the body of the loop, then it is known as Exit controlled loop. In the Exit controlled loop, The block of code in the body of the loop is executed at least once.

Example: do-while loop.

Parts of a Loop in C++

Loops are also known as iteration statements. A loop contains mainly four parts.

  • Initialization expression.
  • Test expression.
  • Update expression.
  • The body of the loop.

Let us try to understand loops in a Reverse engineering manner. First, let us look at an example. Then understand the concept using the example.

Output:

Now we shall breakdown what happened between line number 6 and line number 9.

Initialization Expression

Before we enter into the loop, its control variables must be initialized. In initialization expression(s), we initialize the control variables. The initialization expression is executed only once and it gives the loop variable its first value.

In the example, we have considered. The Initialization Expression is i = 1 in line number 6. Here we have initialized the value of the loop variable i.e i with the value of 1.

Test Expression

We don't want to run the loop forever, the loop has to stop at a certain point where the condition is met. But how will the loop come to know that it has to stop executing the loop body? Test expression decides whether the loop-body will be executed or not. If the test expression evaluates to true i.e., 1. Then the loop-body is executed else the loop gets terminated.

In the example, we have considered. The test Expression is i <= 3 in line number 6. The loop checks this condition before executing the loop body. If the value of the test condition is False, Then the loop-body doesn't get executed.

Update Expression

The update expression changes the value of the loop variable after every execution of the loop body.

In the example, we considered, In line number 6 i++ is the update expression

The Body of the Loop in C++

The statements which need to be repeated again and again are present in the loop-body.

In the example we considered, we wanted to print I love Scaler! 3 times. To do this, we need to execute the line cout << "I love Scaler!\n"; 3 times. Therefore we put the line of code in the body of the loop.

In a nutshell, the example we considered is the for loop. We initialized the value of i=1,test expression as i<=3 and update expression i++. We will understand for loop in a better way later in this article, along with other loops

Iteration Statements in C++

There are mainly 3 types of loops or iteration statements in C++ namely :

We will see how can we print the line Hello Scaler 5 times using different loops.

Let us look at each of the statements one by one.

  • For Loop

Syntax

Example

Output:

Explanation:

  • In the loop, first, the test expression is checked. In the first iteration the value of i is 1 and the condition i<=5 is True as 1 is less than 5. Therefore the body of the loop is executed.
  • Once the loop is executed, the expression is updated, i.e., i++. Now the value of i is 2, again the test expression is checked and the loop body is executed.
  • After 5 iterations, the value of i becomes 6. The condition i<=5 becomes false. Therefore the loop terminates.

Flow Diagram of for Loop

Flow diagram of for loop

  • while statement

Both for loop and while loop are entry-controlled loops. The for loop is used when the number of iterations is known in advance. We use the while loop when the number of iterations is not known in advance. Iterations are based on some Boolean conditions.

Syntax

Example

Output:

Explanation:

  • In the program, first, we need to initialize the iterating variable. In the above example, we have considered i as the iterative variable and set its value to 1.
  • In the while loop, first, the expression is checked. If the expression evaluates to true, then the body of the loop gets executed.
  • We will increment the value of the iterating variable in the loop as per requirement.
  • After execution of the body of the loop, Again the test condition is checked. If the condition expression evaluates to false, Then the control breaks out of the loop.

Flow Diagram of while loop

Flow diagram of while loop

  • do-while Loop

We use Do-While Loop when we want to run a loop at least one time. The loop body is executed once and later the condition is checked. Syntax

Example

Output

Explanation

  • In the above code, we first executed the body of the loop even before checking the condition.
  • In the body of the loop, We will update the value of the iterating variable as per requirement.
  • Once the body of the loop is executed, We will check the condition.
  • If the condition checked is true, we will run through the loop again.

Flow Diagram of do-while Loop

Flow diagram of do-while loop

Range-based for Loop

In C++ 11 standard, a special for loop is added, which is known as range-based for loop. In a range-based for loop, we can iterate through all the elements in an array, containers, or range.

Note: An array is a collection of similar data elements stored at contiguous memory locations.

A container is a holder object that stores a collection of other objects (its elements).

Syntax

Example

Here, we created an array marks[] and the contents of the array were initialized. Later in for loop inside the parenthesis, we first declared a variable (The data type of the variable should be the same as that of the collection which needs to be iterated ) followed by a : followed by a colon, the name of the collection is to be iterated.

In the body of the loop, we will print the value of the iterative variable which in turn contains the value of the collection.

Output

As we can see, through each iteration the iterating variable takes the value of the elements in the array one by one.

What is an Infinite Loop in C++?

We know that the loop will stop executing the code in the loop-body when the condition is met or if it becomes false. What if the condition is never met or the condition is always True? Such cases are known as infinite loops.

Let us look at an infinite loops

Output

We get the line Infinite loop getting printed continuously infinite times in the console.

Important Points

  • When the number of iterations is known beforehand, Use the for loop.
  • When the exact number of iterations is not known but the loop termination condition is known, Use the while loop.
  • When the code needs to be executed at least once, Such as menu-driven programs, use the do-while loop.

Conclusion

  • There are mainly two types of loops or iteration statements, viz. Entry controlled loops and Exit controlled loop.
  • A loop has four parts . Initialization expression, Test expression, Update expression, The body of the loop.
  • for loop and while loop is known as Entry controlled loop and do-while loop is known as Exit controlled loop.
  • The range-based loop is used to iterate through a collection.
  • Loops with a condition evaluate to true always lead to an infinite loop.