Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin while loop

In Kotlin, the while loop is a control flow structure that allows you to repeatedly execute a block of code as long as a specified condition is true. There's also a variation called the do-while loop. This tutorial will introduce you to both of these loops.

1. while Loop

Syntax:

while (condition) {
    // code to be executed
}

The loop will keep executing as long as the condition remains true.

Example:

var counter = 5
while (counter > 0) {
    println("Counter value: $counter")
    counter--
}

Output:

Counter value: 5
Counter value: 4
Counter value: 3
Counter value: 2
Counter value: 1

2. do-while Loop

The do-while loop is similar to the while loop but with a key difference: it checks the condition after executing the loop body. This means the loop body will always execute at least once.

Syntax:

do {
    // code to be executed
} while (condition)

Example:

var counter = 5
do {
    println("Counter value: $counter")
    counter--
} while (counter > 0)

Output:

Counter value: 5
Counter value: 4
Counter value: 3
Counter value: 2
Counter value: 1

Tips and Best Practices:

  1. Beware of Infinite Loops: If the condition in your while or do-while loop never becomes false, the loop will run indefinitely. This can lead to the program becoming unresponsive.

  2. Prefer For-Loops for Known Iterations: If you know beforehand how many times you want to execute a loop (e.g., iterating over a collection or range), a for loop is often a more suitable choice.

  3. Use do-while for Post-Check Iteration: If you have a scenario where you want to ensure the loop body is executed at least once (e.g., a menu system where you prompt a user at least once before checking their input), the do-while loop is ideal.

  4. Keep Loop Bodies Small: For clarity and maintainability, try to keep the body of your loops concise. If the loop's logic becomes complex, consider refactoring some of that logic into separate functions.

Conclusion

The while and do-while loops in Kotlin provide you with tools for creating iterations based on conditions. Understanding how and when to use them can help you craft efficient and readable programs. Remember to always be cautious of conditions that may lead to infinite loops and to choose the loop structure that best matches your specific needs.

1. Conditionals and iteration with while loop in Kotlin:

The while loop in Kotlin allows you to repeatedly execute a block of code while a condition is true.

fun main() {
    var count = 0

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

2. Infinite while loops and exit conditions in Kotlin:

Be cautious with infinite loops. Ensure there is an exit condition to prevent an infinite loop.

fun main() {
    var count = 0

    while (true) {
        println("Count: $count")
        count++

        if (count >= 5) {
            break
        }
    }
}

3. Using break and continue in while loops in Kotlin:

You can use break to exit the loop and continue to skip the rest of the current iteration.

fun main() {
    var count = 0

    while (count < 5) {
        if (count == 2) {
            count++
            continue
        }

        println("Count: $count")

        if (count == 3) {
            break
        }

        count++
    }
}

4. Do-while vs while loop in Kotlin:

The do-while loop guarantees that the block of code is executed at least once, as the condition is checked after the first iteration.

fun main() {
    var count = 0

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

5. Nested while loops in Kotlin:

You can nest while loops to create more complex iteration patterns.

fun main() {
    var outer = 0

    while (outer < 3) {
        var inner = 0

        while (inner < 2) {
            println("Outer: $outer, Inner: $inner")
            inner++
        }

        outer++
    }
}

6. Control flow and logic in Kotlin while loops:

You can use logical operators to create complex conditions in while loops.

fun main() {
    var count = 0

    while (count < 10 && count % 2 == 0) {
        println("Count: $count")
        count += 2
    }
}

7. While loop and user input in Kotlin:

You can use a while loop to repeatedly ask for user input until a specific condition is met.

fun main() {
    var userInput: String

    while (true) {
        print("Enter 'exit' to quit: ")
        userInput = readLine() ?: ""

        if (userInput.toLowerCase() == "exit") {
            break
        }
    }

    println("Exited the loop")
}

8. Using while loop for computations in Kotlin:

while loops can be used for iterative computations.

fun main() {
    var factorial = 1
    var n = 5

    while (n > 0) {
        factorial *= n
        n--
    }

    println("Factorial: $factorial")
}

9. Error handling in while loops in Kotlin:

Handle errors or unexpected input within a while loop.

fun main() {
    var userInput: Int

    while (true) {
        try {
            print("Enter a number: ")
            userInput = readLine()?.toInt() ?: throw NumberFormatException("Invalid input")

            println("Square: ${userInput * userInput}")
            break
        } catch (e: NumberFormatException) {
            println("Invalid input. Please enter a valid number.")
        }
    }
}

10. While loop and lists/arrays in Kotlin:

Iterate over elements in a list or array using a while loop.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    var index = 0

    while (index < numbers.size) {
        println("Element at index $index: ${numbers[index]}")
        index++
    }
}