A while loop is like a repeating game that keeps going as long as you're having fun.
Imagine you’re playing a game where you jump on a trampoline. You keep jumping as long as you feel happy, but the moment you get tired, you stop. That’s how a while loop works in programming: it keeps doing something over and over again while a condition is true.
How It Works
Think of a while loop like this:
- You say, “I will keep jumping as long as I’m happy.”
- You jump once.
- You check if you’re still happy.
- If you are, you jump again.
- If you're not, the game stops.
In programming terms:
- The condition is like checking your happiness.
- The action (jumping) is what keeps happening while the condition is true.
A Real-Life Example
Let’s say you’re eating cookies from a jar. You keep taking one cookie at a time as long as there are still cookies left in the jar. Once the jar is empty, you stop.
That's exactly how a while loop works, it keeps doing something while a condition (like "there are still cookies") stays true.
Examples
- A while loop is like telling a robot to keep walking until it reaches the end of a hallway.
- Imagine counting from 1 to 10, but you don't stop until you get there.
Ask a question
See also
- What are infinite loops?
- Programming vs Coding - What's the difference?
- How Does The importance of considering edge cases in software engineering Work?
- How Does Continue (From This Point) Work?
- What are access violations?