Industrial Training




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  
}  
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< String>){  
    var i = 1  
    while (i<=5){  
        println(i)  
        i++  
    }  
}  
fun main(args: Array< String>){  
    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< String>){  
        while (true){  
        println("infinite loop")  
        }  
}  
fun main(args: Array< String>){  
        while (true){  
        println("infinite loop")  
        }  
} 

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

 
infinite loop
infinite loop
infinite loop
infinite loop


Hi I am Pluto.