📅 Date: Jan 5, 2026
🔥 Topic: While Loop, Do-While Loop & Comparison
🔄 The Other Loops
Yesterday I used the for loop because I knew the exact count. But what if we don't know when to stop? Like waiting for a user to enter the correct password?
That's where While and Do-While come in.
1️⃣ The While Loop (Entry Control)
Checks the condition first, then runs the code. If the condition is false initially, the code never runs.
while (condition) {
// Code runs as long as true
}
2️⃣ The Do-While Loop (Exit Control)
Runs the code first, then checks the condition. This guarantees the code runs at least once.
do {
// Runs at least once
} while (condition);
⚔️ Battle of Loops: When to use what?
| Loop Type | Best Use Case |
|---|---|
| For Loop | When you know the number of iterations (e.g., Array traversal). |
| While Loop | When iterations are unknown (e.g., Reading a file until end). |
| Do-While | When code must run once (e.g., Menu driven programs). |
💻 Day 5 Code: Input Validation
I used a do-while loop to force the user to enter a positive number. It won't let you escape until you obey!
#include <iostream>
using namespace std;
int main() {
int number;
do {
cout << "Enter a positive number: ";
cin >> number;
if(number <= 0) {
cout << "Invalid! Try again." << endl;
}
} while (number <= 0);
cout << "Finally! You entered: " << number << endl;
return 0;
}
💠Thoughts
The do-while loop is perfect for game menus ("Play Again?"). Next, I am excited to learn about Functions to modularize my code.
No comments:
Post a Comment