HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to C++VariablesData TypesOperatorsStringsVectors (vector)Conditions (if / switch)Loops (for / while)FunctionsClasses (OOP)
REFERENCE
📖 Overview
🖥️ Output & Input
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Vector
🔁 Condition & Loop
🧩 Function & Class
C++›Loops (for / while)

Loops (for / while)

Definite repetition with for and conditional repetition with while.

Simple enough for a 5-year-old to understand

for loop

Example code
1
#include <iostream>
2
using namespace std;
3
int main() {
4
for (int i = 1; i <= 3; i++) {
5
cout << i << endl;
1, 2, 3
Output / Input1, 2, 3
6
}
7
return 0;
8
}
Output / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the numbers from 1 to 5 vertically using a for loop.

🎯 Expected output: 1 2 3 4 5

Loading editor…

About this topic

In C++, there are three loop constructs inherited from C: for, while, and do-while. C++11 added the range-based loop, which became the default way to iterate over containers.

The importance of the range-based loop lies not just in brevity, but in safety. Since there is no counter, you cannot make out-of-bounds errors, there is no index arithmetic, and signed-unsigned comparison warnings do not occur. The vast majority of loop bugs are eliminated with this structure.

The only point to watch out for in a range-based loop is copying. Elements are COPIED by default; this is costly for large objects, and if you want to modify an element, the change goes to the copy, not the original container.

What you will learn

  • The four loop structures and their differences
  • Why the range-based loop is preferred
  • The difference between copy and reference
  • Using break and continue

When to use?

If you are traversing all elements of a container, use a range-based loop. If you need an index, the classic for loop is required.

When traversing large objects, use a const reference: the copying cost is eliminated, and protection against accidental modification is provided.

Common mistakes

Wrong

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3};
    for (int n : numbers) {
        n = n * 2;
    }
    for (int n : numbers) {
        cout << n << endl;
    }
    return 0;
}

The loop variable is a COPY of the element; modifying the copy does not reflect on the original container and the output does not change. No error message is received, simply the expected change does not happen. To modify the element, you need to use a reference.

Correct

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3};
    for (int &n : numbers) {
        n = n * 2;
    }
    for (int n : numbers) {
        cout << n << endl;
    }
    return 0;
}

Wrong

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 3) {
        cout << i << endl;
    }
    return 0;
}

Since the counter is not incremented, the condition never becomes false and the loop goes infinite. Forgetting to write the increment in the body when using while is the very common mistake; this error does not occur in for because the increment section is written separately.

Correct

#include <iostream>
using namespace std;

int main() {
    int i = 0;
    while (i < 3) {
        cout << i << endl;
        i++;
    }
    return 0;
}

Wrong

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3};
    for (int i = 0; i < numbers.size(); i++) {
        if (numbers[i] == 2) {
            numbers.erase(numbers.begin() + i);
        }
    }
    cout << numbers.size() << endl;
    return 0;
}

Since subsequent elements shift back by one after deletion, the counter skips an element; furthermore, because the size changes, the condition is recalculated at every step. If there are two consecutive matches, the second one is skipped. For deletion, the iterator returned by erase should be used.

Correct

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3};
    for (auto it = numbers.begin(); it != numbers.end(); ) {
        if (*it == 2) {
            it = numbers.erase(it);
        } else {
            ++it;
        }
    }
    cout << numbers.size() << endl;
    return 0;
}

Frequently asked questions

What do I do if I need an index in a range-based loop?

Use a classic for loop or keep a separate counter outside the loop and increment it at each step. If an index is truly necessary, the classic for loop is clearer; if you just need to print sequence numbers, a separate counter is sufficient.

Why is traversing by const reference recommended?

Two reasons: the copying cost is eliminated, and accidentally modifying the element results in a compilation error. For small types like integers, there is no difference; for strings or large structs, a full copy is created at every step, causing a noticeable slowdown.

Can I break out of a nested loop with a single break?

No, break only breaks the innermost loop. Moving the operation into a function and returning is the most readable solution; a flag variable can also be used, but it clutters the code.

Summary

The default way to iterate over containers is the range-based loop.

The loop variable is a copy by default; use a reference to modify it.

Traversing large objects by const reference is both fast and safe.

When erasing while traversing, the iterator returned by erase is used.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code