5.3 — break and continue
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 3continue: 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 5Loop 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";}Tip: press ← / → to move between lessons, / to search.