Android & Kotlin with the eyes of Abhas

Android & Kotlin with the eyes of Abhas

Difference between While and Do While loops in Kotlin.

Let's understand ' while ' loop first. As we all know loops are used in programming languages ( Here, Kotlin ) to perform some task repeatedly following some conditions. Let's understand this by a real life example, assume you are eating Pizza till your appetite isn't satisfied. Here ' eating Pizza ' is a task that you are repeatedly performing but with a condition and that is only till appetite isn't satisfied. Once appetite is satisfied you will stop eating Pizza. This is known as Looping in programming world.

Now, what is ' while ' loop? While loop is a way of looping in which a block of code will keep repeating as long as the controlling Boolean expression is true. Point here to note is, condition is this case will be of type Boolean.

while( i < 5 ){
 do something
}

Here i<5 will return Boolean and block of code will keep repeating till Boolean expression is true. Once expression becomes false, loop will stop.

Let's take a working example:

fun main(){
    var i = 7
   while(i < 5){
              println("Raghu")
              i ++
}
}

Any guess what is going to happen here? Yep, loop will not be executed because Boolean expression is false from the beginning.

In such cases we use ' do while ' loop where we want to execute block for at least once even if the Boolean expression in while loop is false from the initiation. Let's have a look at it for better understanding:

fun main(){
    var i = 7

   do {
              println("Raghu")
              i ++
} while(i < 5)
}

Now here, ' Raghu ' will be printed once even if the loop condition is false in while loop unlike the previous one and that is the main difference between ' while & do while ' loops in Kotlin. ' do while ' allows you to execute the block of code for at least once.

It is completely dependent on use case what to use when writing code but generally we see very less use of ' do while ' loop in comparison to ' while ' loops. But understanding the difference is always helpful.

 
Share this