Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Conditional Expressions and Loops  ›  Lesson

while and do-while

while 12 minA while loop repeats as long as its condition is true and may run zero times, while a do-while loop runs its body first and checks afterwards, so it always runs at least once.

while and do-while

A for loop is perfect when you know what to walk through. But "keep brewing while there are beans" has no list: you only know when to stop. That is the job of while.

The rule

while checks, then acts; do-while acts, then checks.

var beans = 50
var cups = 0
while (beans >= 18) {
    beans -= 18
    cups++
}
println("$cups cups, $beans g left")   // 2 cups, 14 g left

The condition is tested before each round. If it is false at the start, the body runs zero times.

do-while flips the order: the body runs first, then the condition decides whether to go again. So the body always runs at least once:

do {
    val size = readln()
    println("You chose $size")
} while (size !in listOf("S", "M", "L"))

This is the natural shape for "ask, and ask again if the answer was bad". Kotlin has a neat detail here: a variable declared inside the do body, like size, is visible in the while condition.

Every while loop needs something inside it that moves toward stopping, here beans -= 18. Forget it and the condition never changes, giving an infinite loop.

cups++ adds 1 to a var; cups-- subtracts 1. Both work only on variables, not on vals.

The shortcut

Before writing a loop, answer two questions: "Must the body run at least once?" (yes → do-while, no → while) and "Which line makes the condition eventually false?" If you cannot point to that line, the loop may never end.

Tracing the bean loopStep 1 of 4
  1. Start

    beans = 50. Is 50 ≥ 18? Yes, so run the body: beans = 32, cups = 1.

Drills

Answer fast — trust the rule.

quick drill

var n = 0; while (n > 0) { n-- }. How many times does the body run?

quick drill

var n = 0; do { n++ } while (n > 5). What is n afterwards?

quick drill

Which loop never ends?

quick drill

var t = 100; while (t >= 30) { t -= 30 }. What is t afterwards?

Remember

  • while checks first and may run zero times; do-while always runs once.
  • Point to the line that makes the condition false, or risk an endless loop.
  • Use do-while for "try, then retry if needed".

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainBrewing until the beans run out

The grinder holds 50 grams of beans and each cup uses 18 grams. Write a while loop that brews cups while there are enough beans, and state how many cups it makes and how many grams remain. Then explain when you would choose do-while instead, and what happens if you forget to reduce the beans inside the loop.