All lessons
LESSON 16/53Repeating Things
Controlling a Loop
GOALStop a loop early, or skip a single turn.

break stops a loop completely. continue skips just this turn and jumps to the next. A do…while checks its condition afterwards, so it always runs at least once.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << "runs at least once" << endl;
i++;
} while (i < 1);
for (int n = 1; n <= 10; n++) {
if (n % 2 == 0) continue; // тэгш бол алгасна / skip if even
if (n > 7) break; // 7-оос хойш зогсоно / stop after 7
cout << n << " ";
}
cout << endl;
return 0;
}> what you see
runs at least once 1 3 5 7
//LINE BY LINE
Watch it run
The loop walks n from 1 to 10 — but not all of them get printed.
The three loops side by side
| Loop | Checks its condition | Use it when |
|---|---|---|
for | эхэнд / at the start | эргэлтийн тоо мэдэгдэж байгаа / you know the count |
while | эхэнд / at the start | ямар нэг зүйл болтол / you loop until something happens |
do…while | төгсгөлд / at the end | ядаж нэг удаа ажиллах ёстой / it must run at least once |
// Хэрэглэгчээс зөв утга авах — do…while яг тохирно
int n;
do {
cout << "Enter 1-10: ";
cin >> n;
} while (n < 1 || n > 10);break inside nested loops
break leaves only its own loop. The outer loop carries on.
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (c == 1) break; // зөвхөн дотоод давталт зогсоно
cout << r << c << " ";
}
}> what you see
00 10 20
To stop both, use a flag variable — or move the code into a function and return.