while

4 0 0
                                        

syntax:

while(condition){

     // statement

}

if the condition is true, the statement inside the while loop will keep on running. So, normally, the programmers added an incremental or decremental variable that is link to the condition so that as keeps on looping, it will come to a point where the condition will become false.

===============

fun main(){

     val arr = Array(3){it * 10}

     var i = 0

     while(i < arr.size){

          print("${arr[i]} ")

          i++

     }

}

===============

Result:

0 10 20


syntax:

do{

     // statement

}while(condition)

===============

fun main(){

     val arr = Array(3){it * 10}

     var i = 0

     do{

           print("arr[i] ")

           i++

     }while(i < arr.size)

}

===============

Result:

0 10 20

Note: The while and do while loop functions the same. They keep on looping as long as the condition is true. The only difference is the do while will run first before the condition is check. So, if the condition is false, it will stop but at least it runs the loop body at least once. However the while loop will check the condition first before it runs the loop body. If the condition is false, then the body of statement inside the loop will be skip.

Kotlin ProgrammingWhere stories live. Discover now