5.3 — break and continue

📘 Chapter 5⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

break: leave now#

break jumps out of the loop right away.

C++
for (int i { 1 }; i <= 10; ++i){    if (i == 4)    {        break;    }    std::cout << i << ' ';}
Output
1 2 3

continue: skip to the next round#

continue skips the rest of this trip and starts the next one.

C++
for (int i { 1 }; i <= 6; ++i){    if (i % 2 == 0)    {        continue;   // skip even numbers    }    std::cout << i << ' ';}
Output
1 3 5

Loop forever, break when done#

A common pattern: loop "forever" and break when you are finished.

C++
while (true){    std::cout << "Type a positive number: ";    int n {};    std::cin >> n;     if (n > 0)    {        std::cout << "Thanks!\n";        break;    }    std::cout << "That's not positive. Try again.\n";}
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.