What are while loops?

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:

  1. You say, “I will keep jumping as long as I’m happy.”
  2. You jump once.
  3. You check if you’re still happy.
  4. If you are, you jump again.
  5. 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.

Take the quiz →

Examples

  1. A while loop is like telling a robot to keep walking until it reaches the end of a hallway.
  2. Imagine counting from 1 to 10, but you don't stop until you get there.
  3. A while loop helps a computer repeat something as long as a condition stays true.

Ask a question

See also

Discussion

Recent activity

Categories: Biology · loops· programming· while loop