0
0
Kotlinprogramming~5 mins

While and do-while loops in Kotlin

Choose your learning style9 modes available
Introduction

Loops help you repeat actions without writing the same code many times. While and do-while loops let you repeat code as long as a condition is true.

When you want to keep asking a user for input until they give a valid answer.
When you want to process items in a list until you reach the end.
When you want to repeat a task until a certain condition changes.
When you want to keep checking if a game is over before continuing.
When you want to run a block of code at least once, then repeat it if needed.
Syntax
Kotlin
while (condition) {
    // code to repeat
}

do {
    // code to repeat
} while (condition)

The while loop checks the condition before running the code.

The do-while loop runs the code once before checking the condition.

Examples
This while loop prints numbers 1 to 3.
Kotlin
var count = 1
while (count <= 3) {
    println("Count is $count")
    count++
}
This do-while loop also prints numbers 1 to 3, but runs the code block at least once.
Kotlin
var count = 1
do {
    println("Count is $count")
    count++
} while (count <= 3)
Sample Program

This program shows how while and do-while loops work. The first loop counts down from 5 to 1. The second loop counts up from 1 to 3.

Kotlin
fun main() {
    var number = 5
    println("Using while loop:")
    while (number > 0) {
        println(number)
        number--
    }

    var count = 1
    println("Using do-while loop:")
    do {
        println(count)
        count++
    } while (count <= 3)
}
OutputSuccess
Important Notes

Be careful to change the condition inside the loop, or it may run forever.

do-while loops are useful when you want the code to run at least once.

Summary

While loops check the condition before running the code.

Do-while loops run the code once before checking the condition.

Use loops to repeat tasks easily and avoid writing repeated code.