Topic 18 of 91 3. Control Flow in C++ Interactive Tutorial

Loops in C++: Repeating Instructions With Different Loop Constructs

15 mins read Last updated: 26 Sep 2026 22,500 views

Direct Answer & Core Concept

Writing the same instructions again and again would make your program longer and harder to maintain.

C++ solves this problem with loops.

Loops allow you to execute a block of code repeatedly as long as a specified condition is satisfied. Instead of writing the same instruction multiple times, you can write it once and let the loop handle the repetition.

C++ provides three traditional loop constructs: for, while, and do-while. It also provides the range-based for loop, which makes working with arrays and collections easier.

Detailed Explanation & Mechanics

What Are Loops in C++?

A loop in C++ is a control structure that repeatedly executes a block of statements while a condition is satisfied.

Loops are useful when you need to perform the same task multiple times without writing the same code repeatedly.

For example, if you want to print numbers from 1 to 5, you can use a for loop.

Example: A Simple Loop in C++

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 5; i++) {

        cout << i << endl;
    }

    return 0;
}

Output:

In this example:

  • int i = 1 initializes the loop variable.

  • i <= 5 checks whether the loop should continue.

  • i++ increases the variable by one after each iteration.

  • cout displays the current value.

The loop repeats until the condition becomes false.

Why Are Loops Used in C++?

Loops make programming easier because they reduce repeated code and help automate tasks.

Some common uses of loops include:

  • Printing numbers in a sequence.

  • Calculating the sum of multiple numbers.

  • Displaying multiplication tables.

  • Processing arrays and collections.

  • Reading multiple user inputs.

  • Searching for specific values.

  • Repeating menu options in an application.

  • Performing calculations on large amounts of data.

For example, if you want to print the multiplication table of 5, you can use a loop instead of writing ten separate output statements.

Types of Loops in C++

C++ supports different loop constructs depending on how you want to control repetition.

The main types are:

  1. for loop

  2. while loop

  3. do-while loop

  4. Range-based for loop

The first three are traditional loop constructs. The range-based for loop is a convenient modern C++ feature for iterating over arrays and other ranges.

Let's understand each one with examples.

1. for Loop in C++

A for loop is used when you know how many times you want to repeat a block of code.

It is commonly used for counting operations, printing number sequences, processing arrays, and performing calculations.

Syntax of for Loop

main.cpp
Run Online
for (initialization; condition; update) {

    // Code to execute repeatedly

}

A for loop has three main parts:

PartPurposeExample
InitializationSets the starting valueint i = 1
ConditionChecks whether the loop continuesi <= 5
UpdateChanges the loop variablei++

How Does a for Loop Work?

Suppose you write:

main.cpp
Run Online
for (int i = 1; i <= 5; i++) {
    cout << i << endl;
}

The loop follows these steps:

  1. The variable i starts at 1.

  2. C++ checks whether i <= 5.

  3. If the condition is true, the loop body executes.

  4. The value of i increases by one.

  5. The condition is checked again.

  6. The loop stops when the condition becomes false.

Example 1: Print Numbers From 1 to 10

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {

        cout << i << endl;
    }

    return 0;
}

Output:

Example 2: Print Even Numbers Using for Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 2; i <= 20; i += 2) {

        cout << i << " ";
    }

    return 0;
}

Output:

Here, the variable increases by 2 during every iteration, so only even numbers are printed.

Example 3: Calculate the Sum of Numbers From 1 to 10

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int sum = 0;

    for (int i = 1; i <= 10; i++) {

        sum += i;
    }

    cout << "Total Sum: " << sum;

    return 0;
}

Output:

The loop adds each number to the sum variable.

Example 4: Multiplication Table Using for Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number = 5;

    for (int i = 1; i <= 10; i++) {

        cout << number << " x " << i
             << " = " << number * i << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

When Should You Use a for Loop?

Use a for loop when:

  • You know the number of iterations.

  • You want to count numbers.

  • You need to process an array using an index.

  • You want to calculate totals.

  • You need to repeat an operation a fixed number of times.

2. while Loop in C++

A while loop repeatedly executes a block of code as long as its condition remains true.

It is useful when you do not know in advance how many times a loop needs to run.

Unlike a for loop, initialization and updating are usually written separately.

Syntax of while Loop

main.cpp
Run Online
while (condition) {

    // Code to execute repeatedly

}

The condition is checked before each iteration. If it is false initially, the loop body does not execute.

Example 1: Print Numbers From 1 to 5

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;

    while (i <= 5) {

        cout << i << endl;

        i++;
    }

    return 0;
}

Output:

Explanation

  • First, the variable i is initialized to 1.

  • The while loop checks whether i <= 5.

  • If the condition is true, the number is displayed.

  • The variable increases by one.

  • The process repeats until the condition becomes false.

Example 2: Calculate the Sum Using while Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;
    int sum = 0;

    while (i <= 10) {

        sum += i;

        i++;
    }

    cout << "Total Sum: " << sum;

    return 0;
}

Output:

Example 3: Reverse Counting Using while Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 10;

    while (i >= 1) {

        cout << i << endl;

        i--;
    }

    return 0;
}

Output:

Example 4: Read User Input Until Zero Is Entered

A while loop is particularly useful when the number of inputs is not known in advance.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int number;

    cout << "Enter a number (0 to stop): ";

    cin >> number;

    while (number != 0) {

        cout << "You entered: " << number << endl;

        cout << "Enter another number (0 to stop): ";

        cin >> number;
    }

    cout << "Loop finished.";

    return 0;
}

Sample Input:

Output:

main.cpp
Run Online
You entered: 10
You entered: 20
You entered: 30
Loop finished.

This program continues accepting numbers until the user enters zero.

When Should You Use a while Loop?

Use a while loop when:

  • The number of iterations is unknown.

  • Repetition depends on user input.

  • You need to wait for a condition to change.

  • You are processing data until a particular value is reached.

  • You want to repeat an operation while a condition remains true.

3. do-while Loop in C++

A do-while loop is similar to a while loop, but it checks the condition after executing the loop body.

This means the statements inside a do-while loop execute at least once, even if the condition is false initially.

It is useful when an operation must happen before checking whether repetition is required.

Syntax of do-while Loop

main.cpp
Run Online
do {

    // Code to execute

} while (condition);

Important: A do-while loop requires a semicolon after the closing condition.

Example 1: Print Numbers From 1 to 5

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;

    do {

        cout << i << endl;

        i++;

    } while (i <= 5);

    return 0;
}

Output:

Explanation

  1. The loop starts executing the code inside do.

  2. The current value of i is displayed.

  3. The variable is increased by one.

  4. The condition i <= 5 is checked.

  5. If the condition is true, the loop repeats.

  6. If the condition is false, the loop terminates.

Example 2: do-while Executes at Least Once

This is one of the most important differences between while and do-while.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 10;

    do {

        cout << "Hello C++";

        i++;

    } while (i <= 5);

    return 0;
}

Output:

Even though the condition is false initially, the loop body executes once before checking the condition.

Example 3: Simple Menu Using do-while Loop

A menu-driven program is a common practical application of the do-while loop.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int choice;

    do {

        cout << "\n===== MENU =====" << endl;
        cout << "1. Home" << endl;
        cout << "2. About" << endl;
        cout << "3. Contact" << endl;
        cout << "0. Exit" << endl;

        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {

            case 1:
                cout << "Welcome Home!" << endl;
                break;

            case 2:
                cout << "About Us Page" << endl;
                break;

            case 3:
                cout << "Contact Page" << endl;
                break;

            case 0:
                cout << "Exiting Program..." << endl;
                break;

            default:
                cout << "Invalid Choice!" << endl;
        }

    } while (choice != 0);

    return 0;
}

Sample Output:

main.cpp
Run Online
===== MENU =====
1. Home
2. About
3. Contact
0. Exit
Enter your choice: 1

Welcome Home!

===== MENU =====
1. Home
2. About
3. Contact
0. Exit
Enter your choice: 0

Exiting Program...

The menu appears at least once and continues until the user selects option 0.

When Should You Use a do-while Loop?

Use a do-while loop when:

  • The code must execute at least once.

  • You are creating menu-driven applications.

  • You need to ask users to enter information before checking a condition.

  • You want to repeat an operation after its first execution.

  • You are building simple interactive programs.

4. Range-Based for Loop in C++

C++11 introduced the range-based for loop.

It provides a simpler way to iterate over elements of arrays, containers, and other suitable ranges without manually managing an index variable.

This loop is particularly useful when you want to access every element in a collection.

Syntax of Range-Based for Loop

main.cpp
Run Online
for (data_type variable : collection) {

    // Use the current element

}

Here:

  • data_type specifies the type of each element.

  • variable represents the current element.

  • collection is an array, container, or suitable range.

Example 1: Using Range-Based for Loop With an Array

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int numbers[] = {10, 20, 30, 40, 50};

    for (int number : numbers) {

        cout << number << endl;
    }

    return 0;
}

Output:

Explanation

The loop automatically visits each element of the numbers array.

You do not need to declare an index variable or manually check the array length.

Example 2: Calculate the Sum of Array Elements

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int numbers[] = {10, 20, 30, 40, 50};

    int sum = 0;

    for (int number : numbers) {

        sum += number;
    }

    cout << "Total Sum: " << sum;

    return 0;
}

Output:

Example 3: Modify Array Elements Using References

A range-based loop normally copies each element into its loop variable.

If you want to modify the original elements, use a reference with &.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int numbers[] = {1, 2, 3, 4, 5};

    for (int &number : numbers) {

        number *= 2;
    }

    for (int number : numbers) {

        cout << number << " ";
    }

    return 0;
}

Output:

The reference allows the loop to modify the original array elements.

When Should You Use a Range-Based for Loop?

Use a range-based for loop when:

  • You want to visit every element in an array.

  • You are processing elements in a vector or another container.

  • You do not need the element index.

  • You want simpler and more readable iteration code.

  • You want to modify elements using references.

Difference Between for, while, do-while, and Range-Based for Loops

Each loop construct serves a different purpose.

Featureforwhiledo-whileRange-based for
Condition checkedBefore each iterationBefore each iterationAfter each iterationAutomatically iterates over a range
Minimum executionsZeroZeroOneZero if range is empty
Best useKnown iteration countCondition-based repetitionAt least one executionVisiting collection elements
Manual indexUsually usedUsually usedUsually usedNot required
UpdateUsually in loop headerUsually inside loop bodyUsually inside loop bodyAutomatic iteration

Which Loop Should You Choose?

  • Use for when the number of repetitions is known.

  • Use while when repetition depends on a condition.

  • Use do-while when the code must execute at least once.

  • Use range-based for when you want to visit each element in a collection.

There is no single loop that is best for every situation. Choose the one that makes your program easiest to understand.

Nested Loops in C++

A nested loop is a loop placed inside another loop.

The outer loop controls the overall repetition, while the inner loop executes completely for each iteration of the outer loop.

Nested loops are commonly used for patterns, tables, matrices, and multidimensional arrays.

Example 1: Simple Nested for Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 3; i++) {

        for (int j = 1; j <= 3; j++) {

            cout << i << " " << j << endl;
        }
    }

    return 0;
}

Output:

main.cpp
Run Online
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Explanation

  • The outer loop runs three times.

  • For every outer iteration, the inner loop also runs three times.

  • Therefore, the inner loop executes a total of nine times.

Example 2: Print a Star Pattern Using Nested Loops

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 5; i++) {

        for (int j = 1; j <= i; j++) {

            cout << "* ";
        }

        cout << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
*
* *
* * *
* * * *
* * * * *

The outer loop controls the rows, while the inner loop prints the stars in each row.

Example 3: Multiplication Table Using Nested Loops

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 3; i++) {

        for (int j = 1; j <= 5; j++) {

            cout << i * j << "\t";
        }

        cout << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
1   2   3   4   5
2   4   6   8   10
3   6   9   12  15

Infinite Loops in C++

An infinite loop is a loop that continues executing because its termination condition never becomes false.

Infinite loops can be intentional in some applications, such as servers, event-processing systems, and continuously running programs.

However, an accidental infinite loop can cause a program to consume unnecessary processing time.

Example 1: Infinite for Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (;;) {

        cout << "Running..." << endl;
    }

    return 0;
}

The for loop has no initialization, condition, or update expression. Since there is no condition that becomes false, it continues indefinitely unless something terminates it.

Example 2: Infinite while Loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    while (true) {

        cout << "Hello C++" << endl;
    }

    return 0;
}

The condition is always true, so the loop never ends on its own.

How to Stop an Infinite Loop

You can use a break statement when a specific condition is met.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    int i = 1;

    while (true) {

        if (i > 5) {
            break;
        }

        cout << i << endl;

        i++;
    }

    return 0;
}

Output:

The loop terminates when i becomes greater than 5.

Using break and continue Inside Loops

The break and continue statements are useful when you need additional control over loop execution.

Using break

The break statement immediately terminates the nearest enclosing loop.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {

        if (i == 6) {
            break;
        }

        cout << i << " ";
    }

    return 0;
}

Output:

Using continue

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    for (int i = 1; i <= 10; i++) {

        if (i % 2 == 0) {
            continue;
        }

        cout << i << " ";
    }

    return 0;
}

Output:

This program skips even numbers and prints only odd numbers.

Loop Control Flow in C++

Understanding how a loop executes will make it easier to write correct programs.

Flow of a for Loop

A for loop generally follows this sequence:

  1. Initialization takes place once.

  2. The condition is checked.

  3. If true, the loop body executes.

  4. The update expression executes.

  5. The condition is checked again.

  6. The loop ends when the condition becomes false.

Flow of a while Loop

A while loop follows this sequence:

  1. The condition is checked.

  2. If true, the loop body executes.

  3. The loop body updates the required variables.

  4. The condition is checked again.

  5. The loop terminates when the condition becomes false.

Flow of a do-while Loop

A do-while loop follows this sequence:

  1. The loop body executes.

  2. The condition is checked.

  3. If true, the loop repeats.

  4. If false, the loop terminates.

The main difference is that a do-while loop checks its condition after executing the loop body.

Complete C++ Program Using Different Loops

Let's combine different loop constructs in one practical program.

C++ Code

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {

    // For loop
    cout << "For Loop:" << endl;

    for (int i = 1; i <= 5; i++) {
        cout << i << " ";
    }

    cout << endl << endl;

    // While loop
    cout << "While Loop:" << endl;

    int j = 1;

    while (j <= 5) {
        cout << j << " ";
        j++;
    }

    cout << endl << endl;

    // Do-while loop
    cout << "Do-While Loop:" << endl;

    int k = 1;

    do {
        cout << k << " ";
        k++;
    } while (k <= 5);

    cout << endl << endl;

    // Range-based for loop
    cout << "Range-Based For Loop:" << endl;

    int numbers[] = {10, 20, 30, 40, 50};

    for (int number : numbers) {
        cout << number << " ";
    }

    return 0;
}

Output

main.cpp
Run Online
For Loop:
1 2 3 4 5

While Loop:
1 2 3 4 5

Do-While Loop:
1 2 3 4 5

Range-Based For Loop:
10 20 30 40 50

Explanation

This program demonstrates four different loop constructs:

  • The for loop prints numbers using initialization, condition, and update.

  • The while loop repeats while its condition is true.

  • The do-while loop executes its body before checking the condition.

  • The range-based for loop visits every element in an array.

Although the syntax is different, all four constructs help reduce repeated code.

Common Mistakes When Using Loops in C++

Beginners often make mistakes when writing loops. These mistakes can cause unexpected output, infinite loops, or programs that do not work as expected.

1. Forgetting to Update the Loop Variable

Incorrect:

main.cpp
Run Online
int i = 1;

while (i <= 5) {

    cout << i << endl;
}

The variable i is never increased, so the condition remains true.

Correct:

main.cpp
Run Online
int i = 1;

while (i <= 5) {

    cout << i << endl;

    i++;
}

2. Using the Wrong Loop Condition

Incorrect:

main.cpp
Run Online
for (int i = 1; i < 5; i++) {
    cout << i << endl;
}

This prints numbers only from 1 to 4.

If you want to include 5, use:

main.cpp
Run Online
for (int i = 1; i <= 5; i++) {
    cout << i << endl;
}

3. Adding an Extra Semicolon After a Loop

Incorrect:

main.cpp
Run Online
for (int i = 1; i <= 5; i++);

{
    cout << "Hello";
}

The semicolon creates an empty loop body. The block that follows is separate and executes only once.

Correct:

main.cpp
Run Online
for (int i = 1; i <= 5; i++) {

    cout << "Hello" << endl;
}

4. Forgetting the Semicolon in a do-while Loop

Incorrect:

main.cpp
Run Online
do {
    cout << "Hello";
} while (true)

Correct:

main.cpp
Run Online
do {
    cout << "Hello";
} while (false);

A do-while statement must end with a semicolon.

5. Creating an Accidental Infinite Loop

Always make sure that the loop condition can eventually become false, or that the loop has a suitable exit mechanism.

6. Using continue Incorrectly in a while Loop

Make sure that the loop variable is updated even when a continue statement executes.

Otherwise, the loop may never reach its termination condition.

7. Using the Wrong Starting Value

Always check the initialization value, especially when working with arrays and indexes.

For an array containing five elements, valid indexes are generally 0 to 4.

Best Practices for Writing Loops in C++

Follow these practices to write cleaner and more reliable C++ programs:

  • Choose the loop construct that best matches the task.

  • Use for loops when the number of iterations is known.

  • Use while loops for condition-based repetition.

  • Use do-while when the code must execute at least once.

  • Use range-based for loops to process collection elements.

  • Always check loop conditions carefully.

  • Update loop variables correctly.

  • Avoid accidental infinite loops.

  • Use meaningful variable names.

  • Keep nested loops as simple as possible.

  • Use braces to make loop bodies clear.

  • Use break and continue only when they improve readability.

Frequently Asked Questions About Loops in C++

1. What is a loop in C++?

A loop in C++ is a control structure that repeatedly executes a block of code while a specified condition is satisfied.

2. How many types of loops are there in C++?

C++ has three traditional loop constructs: for, while, and do-while. It also supports the range-based for loop, which is commonly used with arrays and containers.

3. What is a for loop in C++?

A for loop is used to repeat a block of code when the initialization, condition, and update can conveniently be managed in one loop header.

4. What is a while loop in C++?

A while loop repeatedly executes a block of code as long as its condition remains true. The condition is checked before each iteration.

5. What is a do-while loop in C++?

A do-while loop executes the loop body first and checks its condition afterward. Therefore, its body executes at least once.

6. What is the difference between while and do-while loops?

A while loop checks the condition before executing the loop body. A do-while loop checks the condition after executing the body.

7. What is a nested loop in C++?

A nested loop is a loop placed inside another loop. It is commonly used for patterns, tables, matrices, and multidimensional arrays.

8. What is an infinite loop in C++?

An infinite loop is a loop that continues running because its termination condition never becomes false or because it has no terminating condition.

9. Can a for loop run without a condition?

Yes. If the condition is omitted from a for loop, it is treated as true. The loop continues until a jump statement or another mechanism terminates it.

10. What is a range-based for loop in C++?

A range-based for loop is a C++ feature that allows you to visit each element in an array, container, or other suitable range without manually managing an index.

11. Can we use break inside a while loop?

Yes. The break statement can terminate a while loop immediately.

12. What is the use of continue in C++ loops?

The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.

13. Which loop executes at least once in C++?

The do-while loop executes at least once because its condition is checked after the loop body.

14. Which loop is best for beginners in C++?

The for loop is often a good starting point for counting tasks because initialization, condition, and update are written together. However, the best loop depends on the problem.

15. Can loops be nested in C++?

Yes. You can place one loop inside another loop. Nested loops are useful for working with rows and columns, patterns, and multidimensional data.

Runnable Code Example: Loops in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <vector>

int main() {
    // 1. Classic for loop
    std::cout << "For loop: ";
    for (int i = 1; i <= 3; ++i) {
        std::cout << i << " ";
    }
    std::cout << "
";

    // 2. while loop
    int count = 3;
    std::cout << "While loop: ";
    while (count > 0) {
        std::cout << count << " ";
        count--;
    }
    std::cout << "
";

    // 3. do-while loop (guaranteed at least one run)
    int value = 0;
    std::cout << "Do-While loop: ";
    do {
        std::cout << value << " ";
        value++;
    } while (value < 1);
    std::cout << "
";

    // 4. Range-based for loop (Modern C++)
    std::vector<std::string> nodes = {"alpha", "beta", "gamma"};
    std::cout << "Range-based for: ";
    for (const auto& node : nodes) {
        std::cout << "[" << node << "] ";
    }
    std::cout << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: How does a range-based for loop work under the hood?

A: The compiler expands `for (auto&& x : container)` into an equivalent traditional iterator loop calling `auto __begin = std::begin(container); auto __end = std::end(container); for (; __begin != __end; ++__begin)`.
Q

Q: Why should you use const auto& in range-based for loops?

A: Using `const auto&` binds elements by constant reference, preventing expensive object copying (e.g. copying `std::string` or `std::vector`) and guaranteeing read-only safety.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Default to range-based for loops for (const auto& item : container) when inspecting collections.
2. Use for (auto& item : container) when modifying elements in place.
3. Ensure loop termination conditions are reachable to prevent infinite execution.