Kotlin while and do…while Loop

Kotlin while and do…while Loop are indispensable tools in programming, enabling the repetition of a specific block of code until a certain condition is met. In Kotlin, two primary loops are used: the while loop and the do...while loop. This comprehensive guide will explore these loops with detailed explanations and real-world examples to solidify your understanding.

Why Use Loops?

Loops play a crucial role in software development, especially when dealing with repetitive tasks or handling dynamic data. They improve code readability, reduce redundancy, and enhance code efficiency by automating iterative processes.

Kotlin while Loop

The while loop in Kotlin iterates over a block of code as long as a specified condition remains true.

Syntax of while Loop:

while (testExpression) {
    // codes inside the body of while loop
}

How while Loop Works:

  • The testExpression inside the parenthesis is a Boolean expression.
  • If the testExpression evaluates to true, the statements inside the while loop’s body are executed.
  • After execution, the testExpression is evaluated again.
  • This cycle continues until the testExpression evaluates to false, terminating the while loop.

Example 1: Counting Lines

fun main() {
    var i = 1

    while (i <= 5) {
        println("Line $i")
        ++i
    }
}

Output:

Line 1
Line 2
Line 3
Line 4
Line 5

Example 2: Compute Sum of Natural Numbers

fun main() {
    var sum = 0
    var i = 100

    while (i != 0) {
        sum += i     // sum = sum + i;
        --i
    }
    println("Sum = $sum")
}

Output:

Sum = 5050

Example 3: User Authentication Retry

Consider a scenario in a mobile app where you want to prompt the user for login credentials until they enter the correct username and password:

fun main() {
    var loggedIn = false

    while (!loggedIn) {
        val username = getUsernameInput()
        val password = getPasswordInput()

        loggedIn = authenticateUser(username, password)

        if (!loggedIn) {
            println("Invalid credentials. Please try again.")
        }
    }

    println("Login successful. Welcome!")
}

In this example, the while loop ensures that the user keeps trying to log in until successful authentication.

Example 4: Real-World Use Case: Data Processing

In a backend service for processing data, you may use a while loop to handle data retrieval and processing until a certain condition is met:

fun processData() {
    var dataAvailable = true

    while (dataAvailable) {
        val data = fetchData()
        if (data.isNotEmpty()) {
            process(data)
        } else {
            dataAvailable = false
        }
    }

    println("Data processing complete.")
}

Here, the loop continues to fetch and process data until no more data is available.

Kotlin do...while Loop

The do...while loop is similar to the while loop, but it guarantees that the block of code inside the loop is executed at least once, even if the initial condition is false.

Syntax of do...while Loop:

do {
    // codes inside the body of do while loop
} while (testExpression)

How do...while Loop Works:

  • The codes inside the body of the do construct are executed once, regardless of the testExpression.
  • After execution, the testExpression is checked.
  • If the testExpression evaluates to true, the codes inside the loop are executed, and the testExpression is evaluated again.
  • This process continues until the testExpression evaluates to false, terminating the do...while loop.

Example 1: Sum of User-Entered Numbers

fun main() {
    var sum: Int = 0
    var input: String

    do {
        print("Enter an integer: ")
        input = readLine()!!
        sum += input.toInt()
    } while (input != "0")

    println("Sum = $sum")
}

Output (User Input Simulation):

Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: -6
Enter an integer: 0
Sum = 3

In the do...while loop example, the output depends on the user input during program execution. The provided output is a simulation based on user inputs.

Example: User Feedback Survey

Consider a web application that prompts users to provide feedback until they submit valid feedback:

fun collectFeedback() {
    var feedbackValid = false

    do {
        val feedback = promptUserForFeedback()
        feedbackValid = validateFeedback(feedback)

        if (!feedbackValid) {
            println("Invalid feedback. Please provide valid feedback.")
        }
    } while (!feedbackValid)

    println("Thank you for your feedback!")
}

In this example, the do...while loop ensures that users keep providing feedback until it meets validation criteria.

Kotlin’s while and do...while loops are invaluable tools for managing iterative processes and user interactions in software development. By incorporating these loops with real-world examples such as user authentication, data processing, and user feedback collection, you can enhance the functionality and user experience of your Kotlin applications. Experimenting and practicing with these loops will further strengthen your programming skills in Kotlin.