Friday 15 December 2017

Kotlin: while, do-while loops

while loop
while statement executes a block of statements until a particular condition is true

Syntax
while (expression) {
      //statements
}

The expression in the while statement must evaluates to a boolean value, otherwise compiler will throw error. While statement first evaluates the expression, until the expression evaluates to true, it executes the code inside the while block, otherwise it comes out of the while loop.

Example: Print numbers from 0 to 9 using while loop.

WhileDemo.kt
fun main(args: Array<String>) {

 var counter : Int = 0
 
 while(counter < 10){
  println(counter)
  counter++
 }
}

Output
0
1
2
3
4
5
6
7
8
9


do-while loop
do-while is also a loop construct like while, but evaluates its expression at the bottom of the loop instead of the top.

    Syntax
    do {
        //statement(s)
    } while (expression)


DoWhileDemo.kt
fun main(args: Array<String>) {

 var counter : Int = 0
 
 do{
  println(counter)
  counter++
 }while(counter < 10)
}


Output
0
1
2
3
4
5
6
7
8
9

What is the difference between while and do-while ?
Statements within the do block are always execute at least once even if the expression evaluates to false.



Previous                                                 Next                                                 Home

No comments:

Post a Comment