πŸ” What is a while Loop?

A while loop keeps executing a block of code as long as the condition is true.


βœ… Syntax:


while(condition) {
    // loop body (runs repeatedly)
}

πŸ”Ή Before each iteration, the condition is checked.

πŸ”Ή If it’s true β†’ loop runs

πŸ”Ή If false β†’ loop stops


πŸ”Ή Example: Print numbers from 1 to 5


int i = 1;
while(i <= 5) {
    cout << i << " ";
    i++;
}

🧠 Output: 1 2 3 4 5


⚠️ Important:

You must update the loop variable (like i++), or you might create an infinite loop.


πŸ” Real-Life Analogy:

Suppose you’re entering a password β€” and the system keeps asking "Enter again" until you type the correct one.

That’s a perfect use case for a while loop.


πŸ”Έ Infinite Loop Example: