Not every job in the city has a fixed number of steps. Sometimes you need to keep going until a condition changes — like an elevator that keeps climbing until it reaches the right floor. That's where while and do-while loops shine.
The while loop — checks the condition before each iteration. If the condition is false from the start, the body never executes.
Think of it like an elevator with a smart sensor: "Check if we need to go higher. If yes, move up. If no, stop." The sensor checks before the elevator moves.
The do-while loop — guarantees the body runs at least once, then checks the condition. The check happens after the first execution.
This is like a building safety inspector who always performs at least one check — even if someone says "no checks needed," the inspector does one anyway. Safety first! 🔍
Key difference visualized:
while: Check → Run → Check → Run → ... → Check (fails) → Stopdo-while: Run → Check → Run → Check → ... → Check (fails) → Stopwhile might run zero times if the condition is initially falsedo-while always runs at least once, guaranteedHere's a quick proof of the difference:
⚠️ Watch out for infinite loops! Always make sure your condition will eventually become false. If you forget to increment floor inside the while loop, the elevator gets stuck forever — and nobody wants to be trapped in an elevator! 😱