Kotlin Loops

Kotlin provides multiple looping constructs to repeat code execution: for, while, and do-while. Understanding when and how to use each loop is essential for writing clean, efficient code.

1. For Loop

Why use?

The for loop is ideal for iterating over a known range, array, list, or collection. It is concise and readable for fixed iterations.

How to use? Examples:

// Iterating over a range
for (i in 1..5) {
    println(i)
}

// Iterating over a collection with index
val colors = listOf("Red","Green","Blue")
for ((index, color) in colors.withIndex()) {
    println("$index -> $color")
}

// Using step and downTo
for (i in 10 downTo 1 step 2) println(i)

When to use and when not:

Complex Example:

// Nested loop with continue
for (i in 1..3) {
    for (j in 1..3) {
        if (i == j) continue // Skip diagonal elements
        println("i=$i, j=$j")
    }
}

Interview Questions:

2. While Loop

Why use?

The while loop is used when the number of iterations is not known in advance and depends on a runtime condition.

How to use? Examples:

var i = 1
while (i <= 5) {
    println(i)
    i++
}

// Loop based on user input
var input: String
while (true) {
    print("Enter text (type exit to quit): ")
    input = readLine() ?: ""
    if (input == "exit") break
}

When to use and when not:

Complex Example:

// Accumulate sum until a limit
var sum = 0
var number = 1
while (sum < 20) {
    sum += number
    println("Added $number, sum=$sum")
    number++
}

Interview Questions:

3. Do-While Loop

Why use?

The do-while loop guarantees the loop executes at least once before checking the condition.

How to use? Examples:

var i = 1
do {
    println(i)
    i++
} while (i <= 5)

// User input example
var input: String
do {
    print("Enter text (type exit to quit): ")
    input = readLine() ?: ""
} while (input != "exit")

When to use and when not:

Complex Example:

// Input validation example
var age: Int
do {
    print("Enter your age (must be > 0): ")
    age = readLine()?.toIntOrNull() ?: 0
} while (age <= 0)

Interview Questions:

Summary Table

LoopUse CaseKey Point
forKnown iterations, collections, rangesConcise, readable
whileUnknown iterations, runtime conditionsCondition checked before execution
do-whileAt least one execution requiredCondition checked after execution