In this tutorial, you shall learn about the while loop in Kotlin, its syntax, execution flow, and how to use it for condition-based repetition, with examples covering counters, break, continue, and nested conditions.

Kotlin While Loop

A Kotlin while loop repeatedly executes a block of statements as long as its condition evaluates to true. Kotlin checks the condition before entering the loop body, so the body may not execute at all when the condition is initially false.

A while loop is useful when the number of repetitions is not known in advance. Common examples include reading values until valid input is received, processing items until a queue is empty, or repeating an operation while a state remains active.

Kotlin While Loop Syntax

The syntax of While Loop statement is

</>
Copy
while (condition) {
    statements
}
  • while: Kotlin keyword.
  • condition: a boolean expression, or something that evaluates to a boolean value.
  • statements: one or more Kotlin statements. This can be empty as well, if necessary.
  • () parenthesis enclose the condition, and {} curly braces enclose the while loop body.

The condition must have the Kotlin type Boolean. Kotlin does not treat numbers, strings, or nullable values as implicit Boolean conditions.

How a While Loop Executes in Kotlin

  1. The variables used by the loop are initialized.
  2. Kotlin evaluates the condition inside while (...).
  3. If the condition is true, the statements in the loop body execute.
  4. The loop body normally updates a variable or state used by the condition.
  5. Kotlin checks the condition again and repeats the process.
  6. The loop stops when the condition becomes false or a break statement is executed.

A typical counter-controlled while loop therefore has four practical parts: initialization, condition checking, the loop body, and an update expression.

Kotlin While Loop Examples

1. Print Numbers from 1 to N Using a While Loop

In this following program, we will use While Loop to print numbers from 1 to n.

Main.kt

</>
Copy
fun main() {
    var n = 4

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

Output

1
2
3
4

The variable i starts at 1. After each iteration, i++ increases its value. The loop stops after i becomes greater than n.

2. Kotlin While Loop with a Break Statement

In this following example, we will use while loop to print numbers from 1 to infinity. We use break statement inside While Loop to break the loop after printing the number 4.

Kotlin Program – example.kt

</>
Copy
fun main() {
    var i = 1
    while(true){
        println(i)
        i++
        if(i > 4)
            break
    }
}

Output

1
2
3
4

The condition true creates an indefinite loop. The break statement provides the exit condition by terminating the nearest enclosing loop when i > 4.

3. Skip an Iteration with Continue in a Kotlin While Loop

The continue statement skips the remaining statements in the current iteration and returns control to the loop condition. Update the counter before executing continue to avoid repeatedly processing the same value.

</>
Copy
fun main() {
    var number = 0

    while (number < 6) {
        number++

        if (number == 3) {
            continue
        }

        println(number)
    }
}

Output

1
2
4
5
6

When number is 3, continue skips the println() call for that iteration.

4. Count Down with a Kotlin While Loop

A while loop can update its control variable in either direction. The following example decreases a counter until it reaches zero.

</>
Copy
fun main() {
    var count = 5

    while (count > 0) {
        println(count)
        count--
    }

    println("Done")
}

Output

5
4
3
2
1
Done

5. Use Multiple Conditions in a Kotlin While Loop

Logical operators such as &&, ||, and ! can be used to combine Boolean expressions in the while condition.

</>
Copy
fun main() {
    var attempts = 0
    var connected = false

    while (!connected && attempts < 3) {
        attempts++
        println("Connection attempt $attempts")

        if (attempts == 2) {
            connected = true
        }
    }

    println("Connected: $connected")
}

Output

Connection attempt 1
Connection attempt 2
Connected: true

The loop continues only while the connection has not been established and fewer than three attempts have been made.

Kotlin While Loop with Labels

In nested loops, an unlabeled break or continue affects only the nearest enclosing loop. Kotlin labels let you explicitly target an outer loop.

</>
Copy
fun main() {
    var row = 1

    outer@ while (row <= 3) {
        var column = 1

        while (column <= 3) {
            if (row == 2 && column == 2) {
                break@outer
            }

            println("row=$row, column=$column")
            column++
        }

        row++
    }
}

break@outer terminates the loop marked with the outer@ label instead of terminating only the inner loop.

While Loop Versus Do-while Loop in Kotlin

Behaviorwhiledo-while
Condition checkedBefore the loop bodyAfter the loop body
Minimum executionsZeroOne
Typical useRepeat only when a condition is already trueExecute once before deciding whether to repeat

Use while when the operation should not run unless its condition is satisfied. Use do-while when the operation must run at least once, such as displaying a menu before checking whether the user wants to continue.

While Loop Versus For Loop in Kotlin

A Kotlin for loop is usually clearer when iterating over a range, array, collection, or sequence. A while loop is more suitable when repetition depends on a changing condition rather than a known group of values.

  • Use for for values such as 1..10, collection elements, indices, or stepped ranges.
  • Use while when waiting for a state change, validating repeated input, or processing until a stopping condition occurs.
  • Use collection operations such as forEach when applying an action to each element and non-local loop control is not required.

Avoiding Infinite While Loops in Kotlin

An infinite loop occurs when the condition never becomes false and no reachable break statement terminates the loop. For example, forgetting to increment a counter can cause the same condition to remain true indefinitely.

</>
Copy
var i = 1

while (i <= 5) {
    println(i)
    // Missing i++ causes an infinite loop.
}

To prevent unintended infinite loops, confirm that each iteration changes the state used by the condition, or that a reachable exit statement is present.

Common Kotlin While Loop Mistakes

  • Not updating the control variable: The condition remains true and the loop does not finish.
  • Using the wrong comparison operator: For example, using < instead of <= may skip the final expected value.
  • Updating before processing: Incrementing too early can skip the initial value.
  • Placing continue before an update: The counter may never change for the skipped case.
  • Assuming the body always executes: A while loop runs zero times when its initial condition is false.

Kotlin While Loop FAQs

What are the main parts of a Kotlin while loop?

A counter-controlled while loop normally includes initialization, a Boolean condition, the statements executed in each iteration, and an update that eventually makes the condition false.

Can a Kotlin while loop execute zero times?

Yes. Kotlin evaluates the condition before executing the loop body. If the condition is initially false, the body is skipped.

How do I stop a while loop in Kotlin?

You can stop a while loop by allowing its condition to become false or by executing break. In nested loops, a labeled break such as break@outer can terminate a specifically labeled loop.

When should I use while instead of for in Kotlin?

Use while when the number of repetitions is not known beforehand and execution depends on a changing condition. Use for when iterating over a range, collection, array, sequence, or indices.

What is the difference between break and continue in a Kotlin while loop?

break terminates the loop completely. continue skips the remaining statements in the current iteration and proceeds to the next condition check.

Kotlin While Loop Editorial QA Checklist

  • Confirm that every while-loop condition has the Kotlin type Boolean.
  • Check that counter examples update the counter on every applicable path.
  • Verify that examples using continue cannot bypass the required counter update.
  • Confirm that output blocks match the order and number of printed values.
  • Check that labeled break examples identify the correct outer loop.
  • Verify that the distinction between while, do-while, and for is explained accurately.

Further Reading

Conclusion

In this Kotlin Tutorial, we learned how a Kotlin while loop checks a Boolean condition before each iteration. We also covered counter-controlled loops, break, continue, loop labels, multiple conditions, infinite-loop prevention, and the differences between while, do-while, and for loops.