Kotlin while Loop

A while loop keeps executing a block of code as long as a condition remains true. Unlike a for loop (which iterates over a fixed range), a while loop runs until something changes to make the condition false.

while Loop Syntax

var count = 1

while (count <= 5) {
    println("Count: $count")
    count++
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

How while Works


┌─────────────────────────────────────────┐
│  while (condition) {                    │
│                                         │
│   1. Check condition                    │
│       YES → run block → go back to 1    │
│       NO  → exit loop                   │
│  }                                      │
└─────────────────────────────────────────┘

count = 1
  │
  ▼
count <= 5? YES → println, count++ → count = 2
count <= 5? YES → println, count++ → count = 3
count <= 5? YES → println, count++ → count = 4
count <= 5? YES → println, count++ → count = 5
count <= 5? YES → println, count++ → count = 6
count <= 5? NO  → exit loop

do-while Loop

The do-while loop runs the block first, then checks the condition. This guarantees the block runs at least once.

var number = 10

do {
    println("Number: $number")
    number--
} while (number > 7)

Output:

Number: 10
Number: 9
Number: 8

while vs do-while


while:
  Check condition FIRST
  If false at start → block never runs

  var x = 100
  while (x < 10) {
      println(x)   // never runs
  }

do-while:
  Run block FIRST
  Then check condition

  var x = 100
  do {
      println(x)   // prints 100 (runs once)
  } while (x < 10)

Infinite Loop and Manual Exit

Sometimes a loop must run until an external event happens. Use while (true) and break out of it manually:

var input = 0
var total = 0

while (true) {
    input++             // simulating user entering values
    total += input
    if (input == 5) break   // stop after 5 iterations
}

println("Total after 5 steps: $total")  // 15

Avoiding Infinite Loops


DANGER: forgetting to change the condition variable

var count = 1
while (count <= 5) {
    println(count)
    // Missing count++ → count stays 1 forever → infinite loop!
}

SAFE version:
var count = 1
while (count <= 5) {
    println(count)
    count++   ← always update the variable!
}

while Loop with User-Like Input

fun main() {
    val secret = 42
    var guess = 0
    var attempts = 0

    while (guess != secret) {
        attempts++
        guess = (1..100).random()    // simulate guessing
    }

    println("Found $secret after $attempts attempts!")
}

Practical Example: Countdown Timer

fun main() {
    var seconds = 5

    println("Countdown started:")
    while (seconds > 0) {
        println("$seconds...")
        seconds--
    }
    println("Go!")
}

Output:

Countdown started:
5...
4...
3...
2...
1...
Go!

Leave a Comment

Your email address will not be published. Required fields are marked *