Sling Academy
Home/Kotlin/How to Use `do-while` Loops in Kotlin

How to Use `do-while` Loops in Kotlin

Last updated: November 30, 2024

The do-while loop is a variant of the while loop used in many programming languages. In Kotlin, just like in other languages, it executes a block of code at least once before checking the loop's condition.

Basic Syntax

The syntax for a do-while loop in Kotlin is as follows:


do {
    // block of code
} while (condition)

Here, the block of code is executed first, and then the condition is evaluated. If the condition is true, the block of code will execute again. This process continues until the condition evaluates to false.

Example 1: Basic do-while Loop

Let's take a look at a simple example where we use a do-while loop to print numbers from 1 to 5:


fun main() {
    var number = 1
    do {
        println("Number is: $number")
        number++
    } while (number <= 5)
}

In this example, even if the condition is false from the start, the block inside the do section is executed at least once. The loop continues until number reaches a value greater than 5.

Example 2: do-while with User Input

Consider a scenario where we ask the user for a password and continue to prompt them until they enter the correct one:


fun main() {
    val correctPassword = "KotlinRocks"
    var input: String

    do {
        println("Enter your password:")
        input = readLine() ?: ""
    } while (input != correctPassword)

    println("Access granted!")
}

In this case, the loop will continue until the user enters the correct password, demonstrating the use case where initial input always needs to be processed at least once.

When to Use do-while Loops

Opt for a do-while loop when there's a necessity for the loop to execute the code block at least once, irrespective of the condition. One common pattern is when taking user input and validation. It’s especially useful when such an action needs to repeat until a satisfactory input or result is achieved.

Conclusion

The do-while loop is a straightforward, yet powerful looping structure that should be within every Kotlin developer's toolkit. Knowing the scenarios where this loop is more advantageous than a typical while loop can streamline coding tasks and enhance program logic.

Next Article: Difference Between `while` and `do-while` Loops in Kotlin

Previous Article: How to Write a `while` Loop 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