Sling Academy
Home/Kotlin/Difference Between `while` and `do-while` Loops in Kotlin

Difference Between `while` and `do-while` Loops in Kotlin

Last updated: December 05, 2024

Understanding the distinction between while and do-while loops in Kotlin is crucial for writing efficient and predictable code. Both of these constructs are used for executing a block of code repeatedly based on a given condition. However, the primary difference lies in when the condition is evaluated and consequently, how many times the loop executes particularly under false conditions.

Basic Structure

First, let's review their basic syntaxes.

While Loop


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

This while loop continually checks the condition before each loop iteration. If the initial condition is false, the loop's body may not execute at all.

Do-While Loop


var count = 0
do {
    println("Count is: $count")
    count++
} while (count < 5)

The do-while loop executes the loop’s body first and then checks the condition. This guarantees that the statements within the loop are executed at least once, even if the condition is false from the start.

Differences Explained

To understand their differences, let's delve into some specific aspects:

Evaluation Time

  • While Loop: The condition is checked before the body is executed. If the condition is false at the beginning, the loop block will never execute. This is useful when you want to validate the condition before executing the loop body.
  • Do-While Loop: The condition is checked after the code block is executed. This guarantees that the loop will run at least once. It is helpful when at least one iteration of the loop body is necessary regardless the initial condition.

Use Cases

While Loop - A Typical Use Case

The while loop is preferred when the number of iterations is not predetermined, yet the evaluation condition should prevent any iteration when false:


var number = 10
while (number > 0) {
    println("Number is $number")
    number -= 2
}

In this context, the loop decreases the number from 10 to 0. Should number start with 0 or less, the loop would not execute.

Do-While Loop - A Typical Use Case

Consider a menu option input by a user where at least one menu prompt is expected:


var choice: Int

do {
    println("1. Option A")
    println("2. Option B")
    println("Select an option:")
    choice = readLine()?.toIntOrNull() ?: 0
} while (choice !in 1..2)

This do-while loop iterates until user input is within the expected range. Even if the input is valid from the start, at least one prompt occurs.

Considerations

Choosing between while and do-while generally depends on:

  • The necessity of executing the code block at least once.
  • Conditional logic and validations required before performing the looped actions.

In conclusion, both loops serve essential purposes, and knowing when to use each can greatly impact the readability and behavior of your code. Consider future maintainers of your code when deciding as well; clarity often trumps cleverness in collaborative environments.

Next Article: How to Use Infinite Loops in Kotlin (and When to Avoid Them)

Previous Article: How to Use `do-while` Loops in Kotlin

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin