0
0
KotlinHow-ToBeginner · 3 min read

How to Use Do While Loop in Kotlin: Syntax and Examples

In Kotlin, a do while loop executes the code block first and then checks the condition to decide if it should repeat. This guarantees the loop runs at least once. Use the syntax do { /* code */ } while (condition) to create this loop.
📐

Syntax

The do while loop in Kotlin runs the code inside do { } first, then checks the while (condition). If the condition is true, it repeats the loop. This ensures the code runs at least once.

  • do: starts the loop block
  • { }: contains the code to run
  • while (condition): checks if the loop should continue
kotlin
do {
    // code to execute
} while (condition)
💻

Example

This example prints numbers from 1 to 5 using a do while loop. It shows how the loop runs the code first, then checks the condition to continue.

kotlin
fun main() {
    var count = 1
    do {
        println("Count is: $count")
        count++
    } while (count <= 5)
}
Output
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
⚠️

Common Pitfalls

One common mistake is using a do while loop when the condition is false initially, expecting the loop not to run. But do while always runs once before checking. If you want to skip running when the condition is false, use a while loop instead.

Also, forgetting to update variables inside the loop can cause infinite loops.

kotlin
fun main() {
    var x = 10
    // This loop runs once even though condition is false
    do {
        println("x is $x")
    } while (x < 5)

    // Correct way if you want to skip when condition is false
    var y = 10
    while (y < 5) {
        println("y is $y")
    }
}
Output
x is 10
📊

Quick Reference

Remember these tips for do while loops:

  • Runs code block first, then checks condition
  • Always executes at least once
  • Use when you need the loop to run before condition check
  • Update variables inside loop to avoid infinite loops

Key Takeaways

The do while loop runs the code block first, then checks the condition to repeat.
It always executes at least once, even if the condition is false initially.
Use do while when you need the loop to run before checking the condition.
Forgetting to update loop variables can cause infinite loops.
If you want to skip running when condition is false, use a while loop instead.