Table of contents
Text Link

Improve Your Code with Loops in Kotlin

Imagine having to repeatedly write a bunch of elements or repeat something, like memorizing multiplication tables in elementary school. Did you have to write out the entire table with repeated multiplication statements?

If we need to write the multiplication table, we will write something like this:

You can try the code in the link below or see it below. The code is the same.

https://pl.kotl.in/30OaGERjX

fun main() {
    println("1 * 1 = 1")
    println("1 * 2 = 2")
    println("1 * 3 = 3")
    println("1 * 4 = 4")
    println("1 * 5 = 5")
    println("1 * 6 = 6")
    println("1 * 7 = 7")
    println("1 * 8 = 8")
    println("1 * 9 = 9")
    println("1 * 10 = 10")
}

Step one - identify the problem

As you can see, the whole thing becomes too lengthy, and this is only the part of the multiplication table with the digit one. What if you need to write the entire multiplication table? How would you write it?

Here is the whole multiplication table:

(You can find the code on the link below or in the area below the link. The code is identical.)

https://pl.kotl.in/PjvmVIKW5

fun main() {
    println("1 * 1 = 1")
    println("1 * 2 = 2")
    println("1 * 3 = 3")
    println("1 * 4 = 4")
    println("1 * 5 = 5")
    println("1 * 6 = 6")
    println("1 * 7 = 7")
    println("1 * 8 = 8")
    println("1 * 9 = 9")
    println("1 * 10 = 10")
    println("2 * 1 = 2")
    println("2 * 2 = 4")
    println("2 * 3 = 6")
    println("2 * 4 = 8")
    println("2 * 5 = 10")
    println("2 * 6 = 12")
    println("2 * 7 = 14")
    println("2 * 8 = 16")
    println("2 * 9 = 18")
    println("2 * 10 = 20")
    println("3 * 1 = 3")
    println("3 * 2 = 6")
    println("3 * 3 = 9")
    println("3 * 4 = 12")
    println("3 * 5 = 15")
    println("3 * 6 = 18")
    println("3 * 7 = 21")
    println("3 * 8 = 24")
    println("3 * 9 = 27")
    println("3 * 10 = 30")
    println("4 * 1 = 4")
    println("4 * 2 = 8")
    println("4 * 3 = 12")
    println("4 * 4 = 16")
    println("4 * 5 = 20")
    println("4 * 6 = 24")
    println("4 * 7 = 28")
    println("4 * 8 = 32")
    println("4 * 9 = 36")
    println("4 * 10 = 40")
    println("5 * 1 = 5")
    println("5 * 2 = 10")
    println("5 * 3 = 15")
    println("5 * 4 = 20")
    println("5 * 5 = 25")
    println("5 * 6 = 30")
    println("5 * 7 = 35")
    println("5 * 8 = 40")
    println("5 * 9 = 45")
    println("5 * 10 = 50")
    println("6 * 1 = 6")
    println("6 * 2 = 12")
    println("6 * 3 = 18")
    println("6 * 4 = 24")
    println("6 * 5 = 30")
    println("6 * 6 = 36")
    println("6 * 7 = 42")
    println("6 * 8 = 48")
    println("6 * 9 = 54")
    println("6 * 10 = 60")
    println("7 * 1 = 7")
    println("7 * 2 = 14")
    println("7 * 3 = 21")
     println("7 * 4 = 28")
    println("7 * 5 = 35")
    println("7 * 6 = 42")
    println("7 * 7 = 49")
    println("7 * 8 = 56")
    println("7 * 9 = 63")
    println("7 * 10 = 70")
    println("8 * 1 = 8")
    println("8 * 2 = 16")
    println("8 * 3 = 24")
    println("8 * 4 = 32")
    println("8 * 5 = 40")
    println("8 * 6 = 48")
    println("8 * 7 = 56")
    println("8 * 8 = 64")
    println("8 * 9 = 72")
    println("8 * 10 = 80")
    println("9 * 1 = 9")
    println("9 * 2 = 18")
    println("9 * 3 = 27")
    println("9 * 4 = 36")
    println("9 * 5 = 45")
    println("9 * 6 = 54")
    println("9 * 7 = 63")
    println("9 * 8 = 72")
    println("9 * 9 = 81")
    println("9 * 10 = 90")
    println("10 * 1 = 10")
    println("10 * 2 = 20")
    println("10 * 3 = 30")
    println("10 * 4 = 40")
    println("10 * 5 = 50")
    println("10 * 6 = 60")
    println("10 * 7 = 70")
    println("10 * 8 = 80")
    println("10 * 9 = 90")
    println("10 * 10 = 100")
}

That is written in 100 lines.

This is something that is a lot of work, isn’t it?

Step two - turn your question into a solution

Fortunately, every programming language provides us with a tool called a loop.

In Kotlin, we have four types of loops: for, while, do while, and repeat.

Programmers consider the for loop to be the most flexible. Most often, the for loop has such a structure:

You can try the code on the link below or see it in the area below the link. The code matches.

https://pl.kotl.in/RN44DQVvs

fun main() {
    for (i in 1..10) {
        // Here we provide the logic
        // which must be repeated
    }
}

The for loop can be visualized as a rotating circle, with each rotation being called an iteration. We can attach a logic to this circle and repeat it as many times as we need. The for loop has a pointer that points to each iteration, with the constant "i" representing the current iteration number. Using the for loop, we can quickly write the multiplication table and perform other repetitive tasks efficiently.

Check this example code:

You can try the code on the link below or see it in the area below the link. The code matches.

https://pl.kotl.in/UevI7S_GX

fun main() {
    for (i in 1..10) {
        for (j in 1..10) {
            val result = i * j;
            println("$i * $j = $result")
        }
    }
}

 In this example code, we use two nested loops. The external one calculates the first multiplier—1, 2, 3, etc. and the internal one calculates the second multiplier, whose value repeats from 1 to 10 for every value in the external loop.

As you can see, 100 lines of code become just seven if we don’t count the primary method. In Kotlin, the most often used form of for loop expects a range object that can represent closed ranges: “...”

1...4 will represent numbers from 1 to 4. This example loop will print the numbers from 1 to 4:

You can try the code on the link below or see it in the area below the link. The code matches.

https://pl.kotl.in/GVkjxB9Ks

fun main() {
    for(i in 1..4) {
        println(i)
    }
}

or open ranged – e.g., 1..<4.

This example loop will print individual numbers from 1 to 3:

You can try the code on the link below or see it in the area below the link. The code matches.

https://pl.kotl.in/cYV-dHc_S

fun main() {
    for (i in 1..<4) {
        println(i)
    }
}

Step three - use the range expression

Since the range in Kotlin is potent, we can do many things with it.

For instance, we can count backward by using the downTo method of range object:

You can try the sequence of code on the link below, or see it in the area below the link. The code is the same.

https://pl.kotl.in/abtrFDazT

fun main() {
    for (i in 10 downTo 1) {
        println(i)
    }
}

We can use iterator with steps. This example code will iterate with step 3 items through our range:

You can try the code on the link below or see it in the area below the link. There is no difference.

https://pl.kotl.in/-aKf-8UZX

fun main() {
    for (i in 10 downTo 1 step 3) {
        println(i)
    }
}

Loops support two essential things. Break and continue keywords. With them, you can skip iteration or break the current loop completely.

This example will return only one because all other iterations will be skipped.

You can try the code on the link below or see it in the area below the link. The code matches.

https://pl.kotl.in/aGulvcwJk

fun main() {
    for (i in 10 downTo 1 step 3) {
        if (i != 1) {
            continue
        }
        println(i)
    }
}

In the example below, nothing will be printed because the break keyword interrupts the loop immediately.

You can try the code on the link below or see it in the area below the link. The code is the same.

https://pl.kotl.in/dTgWrTnGu

fun main() {
    for (i in 1..6) {
        break
        println(i)
    }
}

As a high-end language, Kotlin supports other valuable loops. For instance, a repeat loop is sound when you want to do something several times and know how many times you want to do it.

You can try the code on the link below or see it in the area below the link. The code is the same.

https://pl.kotl.in/Iu0w3Lh6_

fun main() {
    repeat(3) {
        println("Hello Kotlin!")
    }
}

Master the classic Kotlin loops

There are also a couple of classic loops that Kotlin supports too.

The while loop is a loop where a block of code will repeat until a Boolean expression becomes false. We use this type of loop when we need to perform a task, but we are still determining the number of times we will need to repeat it. For instance, imagine a sink full of dirty dishes. You will keep washing the dishes as long as there are dishes in the sink, right?


Here is an example of the while loop. In this case, we will repeat to print the first hero in the list until there are heroes. It will print Superman, Wonder Woman, and Batman. Every hero is on a new line.

You can try the code on the link below or see it in the area below the link. The code is the same.

https://pl.kotl.in/xd8U4UbxD

fun main() {
    val superHeroes = mutableListOf("Superman", "Wonder Woman", "Batman")
    while (superHeroes.isNotEmpty()) {
        println(superHeroes.removeFirst())
            }
}

The other classic loop that Kotlin supports is a do while loop. It consists of the following structure:

fun main() {
do {
// body
} while (// condition)
}

The loop begins by executing the do loop code block, executed every time, regardless of whether the condition is true or false. After the first iteration, the conditional expression inside the while brackets is evaluated, and the loop continues to the next iteration only if it is evaluated to be true. This evaluation occurs at the end of each iteration inside the do block.

You can check this example code:

fun main() {
    val stopText = "stop"
    var userInput = stopText

    do {
        println("Please enter some text")
        userInput = readln()
        println("You entered $userInput")
    } while (userInput != stopText)

}

This code accepts and prints the range of values until the user types stop.

This is the output of this program:

A computer screen shot of a black screenDescription automatically generated


Conclusion

We have covered the topic of loops in Kotlin. I hope you have enjoyed our journey so far and feel your performance being boosted. To wrap things up, we will provide an example application that can assist someone in studying the multiplication table. This application will test the user on their knowledge of the multiplication table, and if they succeed, it will print the message Congratulations! You know the multiplication table!

un main(args: Array) {

    for (i in 1..10) {
        for (j in 1..10) {
            val result = i * j;
            println("$i * $j = ?")
            var userInput = 0
            while (userInput != result) {
                try {
                    userInput = readln().toInt()
                } catch (ex: NumberFormatException) {
                    println("Please enter numbers!")
                }
                if (userInput != result) {
                    println("Incorrect answer! Please try again")
                }
            }
        }
    }

    println("\uD83C\uDFC6 Congratulations! You know the multiplication table! \uD83C\uDFC6")
}

Share this article
Get more articles
like this
Thank you! Your submission has been received!
Oops! Something went wrong.

Create a free account to access the full topic

Wide range of learning tracks for beginners and experienced developers
Study at your own pace with your personal study plan
Focus on practice and real-world experience
Andrei Maftei
It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.
Get more articles like this