Kotlin – While Loop

Loop is used in programming to repeat a specific block of code until certain condition is met (test expression is false).Loops are what makes computers interesting machines. Imagine you need to print a sentence 50 times on your screen. Well, you can do it by using print statement 50 times (without using loops). How about you need to print a sentence one million times? You need to use loops.You will learn about two loops while and do..while in this article with the help of examples.

Kotlin while Loop

The syntax of while loop is:

while (testExpression) {
    // codes inside body of while loop
}

How while loop works?The test expression inside the parenthesis is a Boolean expression.  If the test expression is evaluated to true,

  • statements inside the while loop are executed.
  • then, the test expression is evaluated again.

This process goes on until the test expression is evaluated to false. If the test expression is evaluated to false,

  • while loop is terminated.

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++
    }
}

Output :

1
2
3
4
5

Notice, ++i statement inside the while loop. After 5 iterations, variable i will be incremented to 6. Then, the test expression i <= 5 is evaluated to false and the loop terminates.

If the body of loop has only one statement, it’s not necessary to use curly braces { }

  • Compute sum of Natural Numbers 1 to 100:
// Program to compute the sum of natural numbers from 1 to 100.
fun main(args: Array<String>) {
    var sum = 0
    var i = 100
    while (i != 0) {
        sum += i // sum = sum + i;
        --i
    }
    println("sum = $sum")
}

Output :

sum = 5050

Here, the variable sum is initialized to 0 and i is initialized to 100. In each iteration of while loop, variable sum is assigned sum + i, and the value of i is decreased by 1 until i is equal to 0.

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.