Kotlin While Loop

In Kotlin, the while loop is a control flow statement that executes a block of code repeatedly while a condition is true.

The general syntax of a while loop is:

while(condition) {
    // code to be executed while the condition is true

The condition is an expression that is evaluated at the beginning of each iteration of the loop. If the condition evaluates to true, the code inside the loop is executed. After the code is executed, the condition is evaluated again, and if it is still true, the code is executed again. This process continues until the condition evaluates to false.

Here’s an example of a while loop that prints the numbers from 1 to 5:

var i = 1
while(i <= 5) {

In this example, the condition is i <= 5, which is true for the first five iterations of the loop. Inside the loop, the value of i is printed, and then incremented by 1 using the i++ statement. After the fifth iteration, the condition i <= 5 is no longer true, and the loop exits.

It’s important to be careful when using a while loop, because if the condition is never false, the loop will continue indefinitely, resulting in an infinite loop. To avoid this, it’s important to ensure that the condition will eventually become false.