Kotlin while Loop

www.igift‮edi‬a.com

In Kotlin, the while loop is a control flow structure that repeatedly executes a block of code as long as a specified condition is true. The basic syntax of the while loop is as follows:

while (condition) {
    // code to execute while condition is true
}

In this syntax, condition is the condition to check, and the while loop executes the code in the block as long as condition is true.

Here's an example that demonstrates the use of the while loop in Kotlin:

fun main() {
    var i = 0
    while (i < 5) {
        println(i)
        i++
    }
}

In this example, the program initializes the variable i to 0, and then enters a while loop that prints the value of i to the console and increments i by 1 on each iteration. The loop continues executing as long as i is less than 5, which means it executes a total of 5 times. The output of the program is as follows:

0
1
2
3
4

It's important to note that the condition in the while loop should eventually become false, otherwise the loop will execute indefinitely, resulting in an infinite loop. In some cases, you may want to use a break or return statement to exit the loop early if a certain condition is met.

fun main() {
    var i = 0
    while (true) {
        if (i == 5) {
            break
        }
        println(i)
        i++
    }
}

In this example, the program uses a while loop with a condition that is always true, and then uses an if statement with a break statement to exit the loop when i is equal to 5. The output of the program is the same as the previous example:

0
1
2
3
4