Loop in C++

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

Loops are used in computer programming to execute a group of instructions or a block of code multiple times without repeatedly writing the same block of code. In this article, we will learn about the loop in C++ and the types of loops. We will learn about basic syntax and an example of for loop, while loop, and do-while loop.

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:

Time complexity: O(1)O(1)

Space complexity: O(1)O(1)

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++

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

  • Entry Controlled loops: 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 actual. Example: For loop and While loop.

  • Exit Controlled Loops: If the condition is checked after executing the block of code in the loop's body, it is known as an Exit controlled loop. In the Exit controlled loop, The block of code in the loop's body is executed at least once. Example: do-while loop.

For loop in C++

Syntax

Example

Output:

Explanation:

  • For loop in C++, the test expression is first checked. In the first iteration, the value of i is one, and the condition i<=5 is True as one is less than 5. Therefore, the body of the for 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 five iterations, the value of i becomes 6. The condition i<=5 becomes false. Therefore, the loop terminates.

Flow diagram of for loop

while loop in C++

Both for loop and while loop are entry-controlled loops. The for loop is used when the number of iterations is known. We use the while loop in c++ 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 considered' i' the iterative variable and set its value to 1.
  • In the while loop, first, the expression is checked. If the expression evaluates to true, the loop's body gets executed.
  • We will increment the value of the iterating variable in the loop as per requirement.
  • After execution of the loop's body, the test condition is checked. If the condition expression evaluates to the false, we can control breaks out of the loop.

Flow diagram of while loop

do-while loop in C++

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 loop's body even before checking the condition.
  • In the loop's body, 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

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 break down 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, giving 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, or 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 updated 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! Three times. To do this, we must execute the line cout << "I love Scaler!\n"; 3 times. Therefore, we put the code line in the loop's body.

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

What is an Infinite Loop in C++?

We know that the loops 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 loop

Output

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

Advantages of Using Loops in C++

1. Code Reusability

Loops allow developers to write code that can be executed multiple times with different inputs or conditions. This not only saves time but also enhances code maintainability by centralizing logic that needs to be executed iteratively.

2. Efficiency

Using loops can significantly improve the efficiency of code execution, especially when dealing with repetitive tasks or large datasets. This results in faster execution times and optimized resource utilization.

3. Maintainability

Loops allow developers to centralize iteration-related logic, making it easier to update, debug, and refactor. This modular approach to code organization improves code maintainability and reduces the risk of introducing errors when making changes to the codebase.

Advanced Looping Techniques

Nested Loops: Nested loops in C++ involve placing one loop inside another. This technique is commonly used for iterating over multi-dimensional arrays or performing operations that require nested iterations.

Code Example:

Explanation:

  • In this example, the outer loop iterates over the variable i from 0 to 2.
  • For each iteration of the outer loop, the inner loop iterates over the variable j from 0 to 2.
  • Inside the inner loop, the indices i and j are printed.

Loop Interchange: Loop interchange swaps the order of nested loops to optimize data access patterns and improve cache performance.

Code Example:

Explanation:

  • In this example, the outer loop iterates over the variable j from 0 to 2.
  • For each outer loop iteration, the inner loop iterates over the variable i from 0 to 2.
  • Accessing the 2D array arr elements in this order may optimize cache performance by improving spatial locality.

Loop Tiling (Blocking): Loop tiling, also known as loop blocking, partitions iterations into smaller blocks to exploit spatial and temporal locality.

Code Example:

Explanation:

  • In this example, the nested loops are partitioned into blocks of a specified size (block_size).
  • The outer loops iterate over blocks of rows and columns of the 2D array arr.
  • The inner loops then process elements within each block, potentially improving cache utilization and reducing memory access latency.

Loop Parallelization (Using OpenMP): Loop parallelization involves distributing loop iterations across multiple threads or processing units to execute them concurrently.

Code Example (OpenMP):

Explanation:

  • OpenMP directives (#pragma omp parallel for) are used to parallelize the loop iteration.
  • The loop iterations are distributed across multiple threads, allowing them to execute concurrently and potentially reducing execution time on multicore processors.
  • In this example, the array arr is initialized in parallel, with each thread responsible for computing a portion of the array elements.

Loop Vectorization: Loop vectorization transforms scalar loops into vectorized ones that simultaneously operate on multiple data elements.

Code Example (Vectorization):

Explanation:

  • The OpenMP directive #pragma omp simd instructs the compiler to vectorize the loop, utilizing SIMD instructions for parallel execution.
  • The loop performs vectorized addition on elements of the vec vector, potentially improving performance by exploiting processor parallelism.
  • In this example, the sum of vector elements is computed after vectorized addition, demonstrating the effectiveness of loop vectorization.

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.
  • Loops with a condition evaluated to true always lead to an infinite loop.
  • Looping statements in C++ offer several advantages, making them powerful tools for controlling program flow and executing repetitive tasks efficiently.
  • Developers can leverage the power of for loop in C++ as it leads to faster development cycles and higher-quality software.