Loops in C++

Loops are fundamental control flow structures in programming that allow the execution of a block of code repeatedly as long as a specified condition is true. In C++, there are three main types of loops: for, while, and do-while.

The for Loop

The for loop in C++ is a powerful construct used for executing a block of code repeatedly based on a specified condition. It’s commonly used when the number of iterations is known in advance.

				
					for (initialization; condition; update) {
    // Code to be executed
}

				
			
  • initialization: This part is executed only once before the loop begins. It’s typically used to initialize loop control variables.
  • condition: This part is evaluated before each iteration of the loop. If it evaluates to true, the loop continues; otherwise, the loop terminates.
  • update: This part is executed after each iteration of the loop. It’s typically used to update loop control variables.

Example: Printing Numbers from 1 to 5

				
					#include <iostream>

int main() {
    for (int i = 1; i <= 5; ++i) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
    return 0;
}

				
			
				
					// output //
1 2 3 4 5
				
			

Explanation:

  • In this example, int i = 1 initializes the loop control variable i to 1.
  • i <= 5 is the condition. As long as i is less than or equal to 5, the loop continues.
  • ++i is the update expression. It increments i by 1 after each iteration.
  • Inside the loop body, std::cout << i << " "; prints the value of i followed by a space.
  • After the loop completes, std::cout << std::endl; prints a newline to move to the next line.

Key Points:

  • The for loop is ideal when you know the number of iterations in advance.
  • It provides a concise and structured way to control the flow of execution in your program.
  • The loop control variables are typically initialized, updated, and tested within the loop header, making the loop self-contained and easy to understand.
  • You can use break and continue statements within the loop to alter its behavior.

The while Loop

The while loop in C++ is a fundamental control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. It’s useful when you want to repeat a set of instructions while a condition remains valid, and the number of iterations isn’t known in advance.

				
					while (condition) {
    // Code to be executed
}

				
			

condition: An expression that evaluates to either true or false. If the condition is true, the loop body will be executed. If false, the loop terminates.

				
					#include <iostream>

int main() {
    int i = 1;
    while (i <= 5) {
        std::cout << "Iteration " << i << std::endl;
        ++i;  // Incrementing the loop control variable
    }
    return 0;
}

				
			
				
					// output //
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5


				
			

Explanation:

  • In this example, the loop begins with the initialization of the loop control variable i to 1.
  • The condition i <= 5 is evaluated. Since i is initially 1, the condition is true, and the loop body is executed.
  • Inside the loop body, “Iteration ” is printed followed by the value of i.
  • The loop control variable i is incremented by 1 (++i) at the end of each iteration.
  • After i reaches 6, the condition i <= 5 becomes false, and the loop terminates.

Key Points

  • Ensure that the loop condition eventually becomes false to prevent an infinite loop.
  • The loop body may contain multiple statements, including control statements like break and continue.
  • If the condition is false initially, the loop body will not be executed at all.

When to Use

  • Use a while loop when the number of iterations is not known beforehand, and you want to repeat a block of code until a specific condition becomes false.
  • It’s commonly used when reading input until a certain condition is met or when implementing algorithms that require iterative steps.

The do-while Loop

The do-while loop in C++ is a control flow statement that repeats a block of code until a specified condition evaluates to false. Unlike the while loop, which tests the condition before executing the loop body, the do-while loop executes the loop body at least once before checking the condition.

				
					do {
    // Code block
} while (condition);

				
			
  • The code block within the do { } braces represents the body of the loop.
  • The condition is a boolean expression that determines whether to continue or terminate the loop.
  • The loop body is executed first, and then the condition is evaluated.
  • If the condition is true, the loop continues to execute; if it’s false, the loop terminates.
				
					#include <iostream>

int main() {
    int i = 1;
    do {
        std::cout << "Iteration " << i << std::endl;
        ++i;
    } while (i <= 5);
    return 0;
}

				
			
				
					// output //
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

				
			

Explanation:

  • In this example, i is initially set to 1.
  • The loop body prints the current value of i and increments it by 1.
  • After each iteration, the condition i <= 5 is checked.
  • The loop continues executing as long as the condition is true (i.e., i is less than or equal to 5).
  • Once i becomes 6, the condition becomes false, and the loop terminates.

Key Points:

  • The do-while loop guarantees that the loop body is executed at least once, even if the condition is initially false.
  • It’s useful when you want to execute a block of code at least once and then repeat it based on a condition.
  • Be cautious with the loop condition to avoid infinite loops. Ensure that the condition becomes false at some point to prevent an infinite loop.

Use Cases:

  • Input Validation: When you need to prompt the user for input at least once and then validate the input in a loop until it meets certain criteria.
  • Menu Driven Programs: When you want to display a menu to the user and execute menu options based on user input until the user chooses to exit.

Nested Loops

Nested loops refer to the situation where one loop is placed inside another loop. This construct allows you to perform repetitive tasks with multiple levels of complexity. Nested loops are commonly used when dealing with multi-dimensional data structures or when performing operations that require iterating over multiple sets of data.

				
					for (initialization; condition; increment/decrement) {
    // Outer loop body
    for (initialization; condition; increment/decrement) {
        // Inner loop body
    }
}

				
			

In the above syntax:

  • The outer loop is usually responsible for controlling the iteration of rows or primary elements.
  • The inner loop is nested within the outer loop and is responsible for controlling the iteration of columns or secondary elements.

Printing Patterns

Nested loops are often used to print patterns or matrices. Let’s take an example of printing a square pattern of asterisks (*):

				
					#include <iostream>

int main() {
    int rows = 5;

    // Outer loop for rows
    for (int i = 1; i <= rows; ++i) {
        // Inner loop for columns
        for (int j = 1; j <= rows; ++j) {
            std::cout << "* ";
        }
        std::cout << std::endl;
    }

    return 0;
}

				
			
				
					// output //
* * * * * 
* * * * * 
* * * * * 
* * * * * 
* * * * * 


				
			

Explanation:

  • In this example, we have an outer loop iterating over rows from 1 to rows.
  • Inside the outer loop, there’s an inner loop iterating over columns from 1 to rows.
  • Each time the inner loop executes, it prints an asterisk (*) followed by a space.
  • After printing all the asterisks in a row, the inner loop moves to the next line by printing std::endl.
  • This process repeats for all rows, resulting in a square pattern of asterisks.

Example: Multiplication Table

Nested loops can also be used to generate multiplication tables:

				
					#include <iostream>

int main() {
    int rows = 10;

    // Outer loop for rows
    for (int i = 1; i <= rows; ++i) {
        // Inner loop for columns
        for (int j = 1; j <= rows; ++j) {
            std::cout << i * j << "\t";
        }
        std::cout << std::endl;
    }

    return 0;
}

				
			
				
					// output //
1   2   3   4   5   6   7   8   9   10  
2   4   6   8   10  12  14  16  18  20  
3   6   9   12  15  18  21  24  27  30  
4   8   12  16  20  24  28  32  36  40  
5   10  15  20  25  30  35  40  45  50  
6   12  18  24  30  36  42  48  54  60  
7   14  21  28  35  42  49  56  63  70  
8   16  24  32  40  48  56  64  72  80  
9   18  27  36  45  54  63  72  81  90  
10  20  30  40  50  60  70  80  90  100 

				
			

Explanation:

  • In this example, we use nested loops to generate a multiplication table up to 10.
  • The outer loop iterates over each row (from 1 to 10).
  • The inner loop calculates and prints the product of the row number (i) and the column number (j).
  • Tab characters (\t) are used to align the output neatly.

Loop Control Statements

C++ provides loop control statements like break, continue, and goto to alter the flow of loops.

  • break: Terminates the loop and transfers control to the statement immediately following the loop.
  • continue: Skips the current iteration of the loop and proceeds to the next iteration.
  • goto: Transfers control to a labeled statement within the same function.

Infinite Loops

An infinite loop is a loop that continues to execute indefinitely. While infinite loops are generally unintended, they can be useful in certain situations, such as when creating programs that continuously listen for user input or run server processes.

				
					#include <iostream>

int main() {
    while (true) {
        std::cout << "This is an infinite loop!" << std::endl;
    }
    return 0;
}

				
			
				
					// output //
This is an infinite loop!
This is an infinite loop!
This is an infinite loop!
...


				
			

Explanation:

  • The condition true in the while loop is always true, causing the loop to repeat indefinitely.
  • To exit an infinite loop, you usually need to manually terminate the program, either by closing the program window or using a termination command (e.g., Ctrl+C).

Range Based for loop

In C++11. Range-based for loops provide a concise way to iterate over elements in a container, such as arrays, vectors, or other iterable data structures.

Syntax of Range-based for Loop:

				
					for (element_type element : container) {
    // Loop body
}

				
			
  • element_type: The data type of each element in the container.
  • element: The variable that represents each element in the container.
  • container: The container to iterate over, such as an array or a standard library container like a vector.

Example: Iterating Over an Array

				
					#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};

    // Iterate over elements in the array
    for (int x : arr) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}

				
			
				
					// output //
1 2 3 4 5

				
			

Explanation:

  • In this example, we have an integer array arr.
  • The range-based for loop iterates over each element x in the array arr.
  • In each iteration, the value of x is printed to the console.

Loop Examples in Real-world Scenarios

Let’s explore some real-world scenarios where loops are commonly used:

  1. Iterating Over an Array: Loops are frequently used to iterate over elements in an array, performing operations on each element.

  2. Processing User Input: Loops are essential for creating interactive programs that repeatedly prompt the user for input until a specific condition is met.

  3. File Processing: Loops can be used to read data from files line by line or perform batch operations on file contents.

  4. Simulation and Modeling: Loops are crucial for simulating dynamic systems or modeling complex phenomena by iteratively updating state variables.

  5. Network Programming: Loops are used in network programming to continuously listen for incoming connections or process incoming data packets.

Loops are fundamental constructs in programming that allow for efficient repetition of code. By understanding the different types of loops, their syntax, and their use cases, you can write more expressive and versatile code to solve a wide range of problems. Whether you're iterating over data structures, handling user input, or implementing complex algorithms, loops are indispensable tools in your programming arsenal.Happy coding! ❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India