Kotlin while Loop with Examples

We use loops in our real life too. Let's take one example - Say I have a bag of balls. Balls are either red color or brown color. We need to distribute these balls into separate buckets. To do this what we generally do - 

1. We pick one ball from the bag.

2. Check its color.

3. If it is red, we put it in the red bucket or if it is brown, we put it in the brown bucket.

4. We do this until the bag is empty.

So we want computers to do the same for us. This is where Loops come into the picture. We keep executing the instructions until the condition is false.

While Loop

Kotlin has different variations of the loop. We will start with the while loop in Kotlin first. 

    	//block of code will be executed until the condition becomes false       

Let's write a program - We need to print a table of a given number. 

  fun main() 
    val num = 2
    var index = 1
    while(index < 11)
    	println(num * index)    
        index = index + 1

Explanation - This loop will run 10 times. Here are the steps -

1. Condition is checked, if it is true, a block of code is executed. 
2. Inside this block of code or body of the loop, the index variable is incremented by 1.
3. Then control again reaches the while loop condition, it again checks if the condition still holds true, if yes then the block of code is executed again.
4. Once the index value reaches 11 (as it is incremented every time), the condition is checked again, and this time it is false loop exits.


Do-while Loop

There is a small difference between the while and do-while loop. In while loops, the condition is checked before executing the code whereas in the do-while condition is checked at the end. So in the case of do-while, body of the loop is executed once no matter what.

Example - 

fun main() {
    var index = 5        
        println("Condition is false but I will be printed")
    while(index < 5)    

Explanation - Here the condition is checked at the end. Thus, body of the loop is executed once. When the execution reaches the end, it checks the condition - if the condition evaluates to true, body of the loop is executed again otherwise loop exits.

NOTE: Do make sure to have a termination condition; otherwise, the loop will run forever, i.e. infinite loop.

That's it for this article. For more articles on Kotlin Tutorials For Beginner Series - refer to this.

Happy Learning !! Cheers From CheezyCode.


Popular posts from this blog

Polymorphism in Kotlin With Example

Create Android Apps - Getting Started