English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin while and do...while loops

Loops are used in programming to repeat a specific code block. In this article, you will learn how to create while and do ... while loops in Kotlin programming.

Loops are used in programming to repeat a specific code block until a certain condition is met (the test expression is false).

Loops make computers an interesting machine. Imagine, you need to print a sentence on the screen50 times. Well, you can use the print statement50 times (without using a loop) to do this. How about printing a million sentences? You need to use a loop.

You will understand the two loops while and do..while in this article's example help

If you are familiar withWhile and do ... while loops in JavaSo you are already familiar with these loops in Kotlin.

Kotlin while Loop

The syntax of the while loop is:

while (testExpression) {
    // The code within the while loop body
{}

How does the while loop work?

The test expression within the parentheses isBooleanexpression.

If the calculation result of the test expression is true,

  • The statements within the while loop will be executed.

  • Then, the test expression is evaluated again.

This process continues until the test expression is evaluated to false.

If the calculation result of the test expression is false,

  • The while loop terminates.

While loop flowchart

Example: Kotlin while loop

//The program prints5times
fun main(args: Array<String>) {
    var i = 1
    while (i <= 5) {
        println("Line $i")
        ++i
    {}
{}

When running the program, the output is:

Line 1
Line 2
Line 3
Line 4
Line 5

Note that the while loop contains ++i statement. In5iteration after, the variable i will increase6. Then, the test expression i <= 5 The evaluation is false, and the loop terminates.

If the loop body contains only one statement, it is not necessary to use braces { }. 

Example: Calculate the sum of natural numbers

//The program calculates1to10The sum of natural numbers 0.
fun main(args: Array<String>) {
    var sum = 0
    var i = 100
    while (i != 0) {
        sum += i     // sum = sum + i;
        --i
    {}
    println("sum = $sum")
{}

When running the program, the output is:

sum = 5050

Here, the variable sum is initialized to 0, and i is initialized to 100. In each iteration of the while loop, the sum variable is assigned sum + i, and the value of i decreases1until i equals 0.

The1iteration: sum = 0+100 = 100, i = 99
The2iteration: sum = 100+99 = 199, i = 98
The3iteration: sum = 199+98 = 297, i = 97
... .. ...
... .. ...
The99iteration: sum = 5047+2 = 5049, i = 1
The100 iterations: sum = 5049+1 = 5050, i = 0 (loop termination)

For more information about the test expression and how it is evaluated, please visitComparisonAndLogical operators.

Kotlin do... while loop

The do...while loop is similar to the while loop with a key difference in the loop. The do...while loop body is executed once before checking the test expression.

The syntax is:

do {
   //Code inside the do...while loop body
}

How does the do...while loop work?

The code inside the do body is executed once (without checking testExpression). Then, the test expression is checked.

If the test expression is evaluated to true, the code within the loop body is executed, and then the test expression is evaluated again. This process continues until the test expression is evaluated to false.

The do..while loop terminates when the test expression evaluates to false.

Flowchart of do ... while loop

Example: Kotlin do ... while loop

The following program calculates the sum of the numbers entered by the user until the user enters 0.

To accept user input, use the readline() function.Recommended Reading: Kotlin Input

fun main(args: Array<String>) {
    var sum: Int = 0
    var input: String
    do {
        print("Enter an integer: ")
        input = readLine()!!
        sum += input.toInt()
    while (input != "0")
    println("sum = $sum")
{}

When you run the program, the output will be as follows:

Enter an integer: 4
Enter an integer: 3
Enter an integer: 2
Enter an integer: -6
Enter an integer: 0
sum = 3