Do While Loop

Learn how a do-while loop runs once first, then repeats while the condition stays true.

Do While Loop

A do-while loop is useful when you want the block to run at least once before checking the condition.

That makes it different from a regular while loop.

Basic Example

Execute at least once:

dhoro x = 0

koro {
    lekho(x)
    x++
} jotokkhon ( x < 10)


This loop prints the value first and only then checks whether it should continue.

How It Works

The do-while structure always runs the body once.

After that first run, it checks the condition.

That means:

  • the body runs at least once
  • the condition is checked after the body
  • the loop keeps repeating only if the condition stays true

Step-by-Step Breakdown

  1. x starts at 0
  2. The body runs once
  3. lekho(x) prints the current value
  4. x++ increases the counter
  5. The condition is checked after the first run
  6. The loop repeats while the condition remains true

Why Use a Do While Loop?

Use a do-while loop when:

  • you want the code to run at least once
  • you want to show a menu before checking for another round
  • you want to try an action before deciding whether to continue

Try These Variations

Practice with different examples:

dhoro n = 1

koro {
    lekho(n)
    n++
} jotokkhon (n <= 3)
dhoro tries = 0

koro {
    lekho("Trying again")
    tries++
} jotokkhon (tries < 2)
dhoro active = sotto

koro {
    lekho("This runs once")
    active = mittha
} jotokkhon (active == sotto)

Common Mistakes

Beginners often make these mistakes:

  • forgetting that the body runs once before the check
  • writing the condition in the wrong place
  • expecting it to behave exactly like a while loop
  • failing to update the value inside the loop

Practice Task

Try writing do-while loops that:

  1. print a number at least once
  2. show a retry message
  3. count up until a limit is reached

Quick Checklist

Before moving on, make sure you can:

  • explain why do-while runs at least once
  • place the condition after the body
  • update the value so the loop can stop
  • compare it with a regular while loop

If yes, you understand the basic idea of the do-while loop.