Loop = Repeat a block of code multiple times until a condition is met.
C++ supports three main types of loops:
| Loop Type | When to Use |
|---|---|
for |
When number of repetitions is known |
while |
When number of repetitions is unknown |
do-while |
When loop must run at least once |
Imagine printing "Hello World" 10 times:
cout << "Hello World\n";
cout << "Hello World\n";
// repeat 10 times 😫
for(int i = 0; i < 10; i++) {
cout << "Hello World\n";
}
Much cleaner and faster to write!
| Loop Type | Structure |
|---|---|
for |
for(init; condition; update) { // code } |
while |
while(condition) { // code } |
do-while |
do { // code } while(condition); |
| Scenario | Use Loop? |
|---|---|
| Printing numbers 1 to 100 | ✅ Yes |
| Keep asking for password until correct | ✅ Yes |
| Run a menu-driven program (like calculator) | ✅ Yes |