Curriculum / C++ / Lesson 07

Loops in C++

C++ supports the same for, while, and do-while loops as C, plus a modern addition: the range-based for loop, which iterates directly over a container's elements without manual indexing..

7 of 10
beginner 📖 5 min read 🎯 1 question

Loops

C++ supports the same for, while, and do-while loops as C, plus a modern addition: the range-based for loop, which iterates directly over a container's elements without manual indexing.

💡 Key insight The range-based for loop, introduced in C++11, is now the preferred way to iterate over arrays and containers like vectors.

Syntax

syntax
for (init; condition; update) { }
for (type item : container) { }  // range-based

Example

The range-based loop reads each element of nums in turn, without needing an index variable.

cpp
#include <iostream>
using namespace std;

int main() {
    int nums[] = {1, 2, 3, 4, 5};
    for (int n : nums) {
        cout << n << " ";
    }
    cout << endl;
    return 0;
}
output1 2 3 4 5

Try it yourself

Copy this example into the C++ compiler and run it — try changing a value and see what happens.

Quick Quiz

1. What C++11 feature lets you loop over an array's elements without an index variable?

Back to curriculum