Table of contents
1.
Introduction
2.
Using Loops
2.1.
For Loop
2.1.1.
Syntax
2.1.2.
Flow Diagram of for loop
2.2.
While Loop
2.2.1.
Syntax:
2.2.2.
Flow Diagram of while loop:
2.3.
Do-while loop
2.3.1.
Syntax:
2.3.2.
Flow Diagram of the do-while loop:
3.
What about an Infinite Loop?
3.1.
Using For loop
3.2.
Using While loop
3.3.
Using the Do-While loop
4.
Advantages
5.
Frequently Asked Questions
5.1.
What is the difference between a for loop & a while loop?
5.2.
Can a loop have multiple conditions?
5.3.
How can I avoid infinite loops?
6.
Conclusion
Last Updated: Nov 24, 2024
Easy

Loop in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Loops are a fundamental concept in programming that allows you to repeat a block of code multiple times. In C++, loops are used to execute a set of instructions repeatedly until a specific condition is met. Loops help us automate repetitive tasks and make code more efficient. Loops make your code cleaner and more readable. 

Loop in C++

In this article, we will discuss the different types of loops in C++, which are for loops, while loops, and do-while loops. 

Using Loops

In C++, there are three main types of loops: for loops, while loops, and do-while loops. Let's discuss each loop type in detail.

For Loop

The for loop is used when you know the exact number of times you want to repeat a block of code. It is often used to iterate over arrays or perform a specific task a certain number of times.

Syntax

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


In this syntax: 

  • Initialization: This is where you initialize the loop variable, which is typically an integer. It is executed only once at the beginning of the loop.
     
  • Condition: This is a boolean expression that is checked before each iteration. If the condition is true, the loop continues. If it is false, the loop terminates.
     
  • Update: This is where you modify the loop variable, usually by incrementing or decrementing its value. It is executed at the end of each iteration.

Flow Diagram of for loop

   +------------+
   |            |
   |  initialize|
   |            |
   +-----+------+
         |
         |
         v
   +-----+------+
   |            |
   |  condition |
   |            |
   +-----+------+
         |
         | true
         v
   +-----+------+
   |            |
   |    code    |
   |   block    |
   |            |
   +-----+------+
         |
         |
         v
   +-----+------+
   |            |
   |   update   |
   |            |
   +-----+------+
         |
         |
         v
   +-----+------+
   |            |
   |    end     |
   |            |
   +------------+

 

Where we can use For loop:

  • The for loop is ideal when you know the exact number of times you want to repeat a block of code.
     
  • It is commonly used for iterating over a range of numbers, such as printing numbers from 1 to 10.
     
  • The for loop is handy for processing each character in a string or each element in a vector.
     
  • It can be used to calculate the sum or product of a series of numbers.
     
  • The for loop is used to implement nested loops, where one loop is placed inside another to perform more complex iterations.
     

For Example:

for (int i = 0; i < 5; i++) {
    cout << "Iteration " << i << endl;
}

While Loop

The while loop is used when you want to repeat a block of code as long as a specific condition is true. The loop continues until the condition becomes false.

Syntax:

while (condition) {
    // code block to be executed
}


Flow Diagram of while loop:

   +------------+
   |            |
   |  condition |
   |            |
   +-----+------+
         |
         | true
         v
   +-----+------+
   |            |
   |    code    |
   |   block    |
   |            |
   +-----+------+
         |
         |
         v
   +-----+------+
   |            |
   |    end     |
   |            |
   +------------+


The while loop checks the condition before each iteration. If the condition is true, the code block is executed. This process repeats until the condition becomes false.

Where we can use the While loop:

  • The while loop is used when you want to repeat a block of code as long as a specific condition is true.
     
  • It is suitable for scenarios where the number of iterations is not known in advance and depends on a certain condition.
     
  • The while loop is commonly used for reading user input until a specific value is entered or a certain condition is met.
     
  • It is handy for implementing game loops or menu systems where the loop continues until the user chooses to exit.
     
  • The while loop can be used to process data or perform calculations until a desired result or state is achieved.

Example:

int num = 0;
while (num < 10) {
    cout << "Enter a number: ";
    cin >> num;
}

Do-while loop

 The do-while loop is similar to the while loop but with one key difference: the code block is executed at least once, regardless of the condition. The condition is checked after the first iteration.

Syntax:

do {
    // code block to be executed
} while (condition);

Flow Diagram of the do-while loop:

   +------------+
   |            |
   |    code    |
   |   block    |
   |            |
   +-----+------+
         |
         |
         v
   +-----+------+
   |            |
   |  condition |
   |            |
   +-----+------+
         |
         | true
         v
   +-----+------+
   |            |
   |    end     |
   |            |
   +------------+


The do-while loop executes the code block first & then checks the condition. If the condition is true, the loop continues to the next iteration. This process repeats until the condition becomes false.

When can we use this : 
 

  • The do-while loop is similar to the while loop but ensures that the code block is executed at least once before checking the condition.
     
  • It is useful when you want to execute a block of code at least once, regardless of the initial condition.
     
  • The do-while loop is often used for validating user input, where you prompt the user for input and then validate it in the loop condition.
     
  • It can be used to implement menu systems where the menu is displayed at least once before checking the user's choice.
     
  • The do-while loop is handy when you need to perform a certain operation or calculation at least once and then repeat it based on a condition.


Example: 

int choice;
do {
    cout << "1. Option 1\n";
    cout << "2. Option 2\n";
    cout << "3. Exit\n";
    cout << "Enter your choice: ";
    cin >> choice;
} while (choice != 3);

What about an Infinite Loop?

An infinite loop is a loop that runs forever because the condition never becomes false. This can happen if the condition is always true or if there is no update statement that modifies the loop variable.

Using For loop

for (int i = 0; i >= 0; i++) {
    // code block
}


In this example, the condition i >= 0 is always true because i is initialized to 0 & keeps increasing with each iteration. This results in an infinite loop.

Using While loop

int i = 0;
while (i < 10) {
    // code block
    // missing update statement
}


Here, the condition i < 10 is true, but there is no update statement that increments the value of i. Consequently, the loop runs indefinitely.

Using the Do-While loop

int i = 0;
do {
    // code block
    // missing update statement
} while (i < 10);


Similar to the previous example, the absence of an update statement leads to an infinite loop.

Point to remember: Infinite loops can cause programs to hang or crash, so it's crucial to ensure that loop conditions eventually become false & that there are appropriate update statements.

Advantages

1. Code reusability: Loops allow you to write a block of code once and execute it multiple times, reducing code duplication and making your program more concise and maintainable.
 

2. Efficiency: Loops help automate repetitive tasks, saving time & effort compared to writing the same code multiple times.
 

3. Iteration over data structures: Loops are essential for iterating over arrays, vectors, or other data structures, enabling you to process each element efficiently.
 

4. Flexibility: Loops provide flexibility in controlling the number of iterations based on specific conditions or user input.
 

5. Readability: When used appropriately, loops can make your code more readable & easier to understand by clearly defining the repetitive tasks.
 

6. Simplified problem-solving: Loops break down complex problems into smaller, manageable parts, allowing you to focus on the logic for a single iteration.
 

7. Faster execution: Loops optimize the execution time of repetitive tasks, as the compiler can often optimize the loop code for better performance.

Frequently Asked Questions

What is the difference between a for loop & a while loop?

A for loop is used when you know the exact number of iterations, while a while loop is used when the number of iterations is not known in advance & depends on a condition.

Can a loop have multiple conditions?

Yes, you can combine multiple conditions using logical operators like && (and) or || (or) to create more complex loop conditions.

How can I avoid infinite loops?

To avoid infinite loops, ensure that the loop condition eventually becomes false. Double-check your condition & make sure there is an update statement that modifies the loop variable in a way that leads to the condition becoming false.

Conclusion

In this article, we have learned about the different types of loops in C++: for loops, while loops, and do-while loops. We have discussed their syntax, flow diagrams, use cases, and examples to understand how they work. Loops are a fundamental concept in programming that allows us to repeat a block of code multiple times, making our programs more efficient and maintainable. 

You can also check out our other blogs on Code360.

Live masterclass