🔁 C++ while Loop – Repeat Until Condition Fails
The while loop repeats code as long as a condition remains true. It’s like telling your program: “Keep going until I say stop!” 🛑➡️
🧠 Syntax of while Loop
while (condition) {
// code to repeat
}
The condition is checked before each repetition. If it’s true, the loop runs again. If false, the loop exits.
🔧 Example: Print Numbers 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 5) {
cout << "i = " << i << endl;
i++;
}
return 0;
}
⚠️ Infinite Loop Warning
If the condition never becomes false, the loop runs forever (called an infinite loop). Like this:
while (true) {
// This will run forever!
}
Always make sure your loop has a way to exit. 🚪
🎯 When to Use while?
- When you don’t know ahead of time how many times to repeat.
- For input loops, game loops, waiting for user actions, etc.
The while loop is like a loyal but cautious friend—it checks before it acts! 😄