Skip to main content

Kotlin While Loop

Kotlin while Loop
The while loop is used to iterate a part of program several time. Loop executed the block of code until the condition has true. Kotlin while loop is similar to Java while loop.

Syntax
while(condition){
    //body of loop
}


 Example of while Loop
Let's see a simple example of while loop printing value from 1 to 5.

 fun main(args: Array){
    var i = 1
    while (i<=5){
        println(i)
        i++    
    }
}


Output:
1
2
3
4
5


Kotlin Infinite while Loop
The while loop executes a block of code to infinite times, if while condition remain true.

 For example:
    fun main(args: Array
){
        while (true){
            println("infinite loop")
        }
      }


Output:
infinite loop
infinite loop
infinite loop
. . . . infinite loop
infinite loop


infinite loop
infinite loop
infinite loop
infinite loop

Comments