A while loop is like a toy that keeps going as long as you press its button, it stops when you stop pressing.
Imagine you have a bouncy ball, and every time it bounces, it says “I’m still playing!” If you keep pushing it down, it will keep bouncing. But if you let go, it stops.
That’s how a while loop works in C++. It keeps doing something, like bouncing, as long as a certain condition is true, like your hand holding the ball down.
The Loop's Rule
The while loop has one important rule: “As long as this is true, keep going!”
For example:
while (ballIsBouncing)
{
// bounce again!
}
It checks if ballIsBouncing is true. If it is, the loop runs, like a bounce. Then it checks again. If you stop pushing (ballIsBouncing becomes false), the loop stops.
When It Stops
The while loop will keep running until the condition becomes false, just like your bouncy ball will stop bouncing when you let go.
So, if you're playing with a toy that keeps doing something over and over, it's like a while loop, fun, simple, and very easy to understand!
Examples
- A while loop is like a repeating alarm clock that keeps ringing until you turn it off.
Ask a question
See also
- What are implicit parameters?
- How Recursion Works?
- What are persistent data structures?
- What is pass-by-reference?
- What are tagged unions?