do-while
A do-while loop checks its condition at the end, so the block always runs at least once. It is perfect for menus and “ask again” input:
#include <iostream>
using namespace std;
int main() {
int guess;
do {
cout << "Guess the number (1-10): ";
cin >> guess;
} while (guess != 7);
cout << "Correct!\n";
return 0;
}Input (what the user types)
3 9 7
Output
Guess the number (1-10): Guess the number (1-10): Guess the number (1-10): Correct!
Common mistake: A
do-whileends with a semicolon after the condition:} while (guess != 7);
break: leave the loop now
break stops the loop immediately, even if the condition is still true:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
cout << "Loop finished early\n";
return 0;
}Output
1 2 3 Loop finished early
continue: skip to the next round
continue skips the rest of this round and jumps to the next one:
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue; // skip 3, 6 and 9
}
cout << i << " ";
}
cout << "\n";
return 0;
}Output
1 2 4 5 7 8 10
Think of it like this:
breakis leaving the cinema in the middle of the film.continueis skipping one boring song but staying for the rest of the playlist.