Kotlin Loop

Loops are very important in programming and you’ll be using them very often. Unlike most other languages, Kotlin loops are expressive. We can understand what the code does by just looking at it. So, before diving into the syntax and examples of loops in Kotlin, let’s look at why loops are needed.

Why we need to use looping?

Suppose we want to display the numbers 1 to 10 on screen. What do we do? We can write print() statements 10 times. What if we want to display 1000 numbers on the screen. Then how inefficient would it be to write 1000 lines of print()! Thank god! Loops are there to save us. In Kotlin, if we want to display the numbers 1 to 1000 on screen, it takes only two lines of code.

for (a in 1..1000)
        println(a)

That’s it. Now this is why we use loops.

Take a look at the loop block diagram:

kotlin loop flowchart

When a loop starts executing, it first checks the loop condition. If the condition is true, the loop body is executed. Then the control returns to the loop condition. The condition is checked again. If it’s true, the loop body is executed again. The process goes on till the condition is false.

For loops in Kotlin

We’ve just seen a for loop in action. Looping is also called iteration. If you hear iteration somewhere just know it’s nothing other than looping. In Kotlin, for loops uses something called range. A range is something between two values. The operator for specifying a range is .. (two dots). For example when we write, 1..100, it means, the numbers from 1 to 100 with both numbers included.

Consider the following code:

for (a in 1..1000)
        println(a)

It’s a simple for loop. It executes 1000 times. Each time the loop repeats, the value of a will advance to the next number in the range. When the loop has first executed the value of a will be 1. Then it is printed. Now the control comes back to the loop again. The value of a is now the second number in the range. That is 2. It is printed. The process goes on until the range is exhausted.
The .. operator is same as using the function rangeTo(). Using .. operator is more convenient. This is perfectly fine.

for (a in 0.rangeTo(100))
        println(a)


We can iterate over a collection of objects like arrays or list with a for loop. I will explain it when we learn about arrays and list. We need not worry about it for now.

What if we want to print multiples of 5 in the range 1 to 100?

fun main(args: Array<String>) {
    for (a in 0..100 step 5)
        println(a)
}

We use the keyword step in this case. It will iterate over the range but it will step 5 positions in every iteration.

downTo() – Iterating in the reverse direction

So far we’ve seen loops going from a lower value to a higher value. What if we have to iterate in the reverse direction? That is, if we want to iterate from 100 to 1. Is it possible in Kotlin? Totally possible!

for (a in 100.downTo(1))
        println(a)

We use the function downTo() for this. As you can see, it will come down from 100 to 1. Stepping can be added in this case also.

for (a in 100.downTo(1) step 5)
        println(a)

Is for the only way to loop in Kotlin? Of course not! There are other loops like while and do…while available. Let’s look at them now.

While loop in Kotlin

while accepts a condition and the loop executes as long as the condition evaluates to true. It’s very simple. Consider the code:

var a = 0
    while(a<100){
        println(a)
        a++
    }

The condition in the while is a<100. The loops will continue repeating as long as the condition is true. Notice the statement a++. It is the short form of saying a=a+1. We’re incrementing the value of variable a each time the loop executes. Otherwise the loop will never end. It’s a condition that we’ll encounter many times while we’re programming. Infinite loops! When we forget to update the value of variable, the loop never cease to end. Keep in mind that at some point, we’ll have to end the loop. We can create an infinite loop like this:

while(true){
        println("Hello")
    }

The loop will never end. It will keep on printing “Hello” to the screen.

do..while loop in Kotlin

See this code:

    var a = 0
    do {
        println(a)
        a++
    } while (a < 100)

do…while is similar to while loop except for one difference. In a do..while loop, the condition is checked at the end of the loop. It makes a big difference to do..while loops. What is it? It executes at least once. For a while loop, if the condition is false, the loop will not execute even once. For do..while loops, as the condition is checked at the end, there is surety, the loop will execute at least once after which the condition is checked for the first time.

break and continue statements in Kotlin

The break statement will break out of a loop. It will end a loop prematurely. You can break the loop based on some condition. If you’re inside a nested loop (a loop inside another loop) you can add a label to the break statement and specify which loop to break.

 labelx@ for (a in 1..20)
        for (b in 1..10)
            println(b)
            if (b == 5)
                break@labelx

Here we labeled the outer loop as labelx. We check for a condition inside the inner loop and when b = 5, we break the outer loop. Thus the loop will stop execution there.

Continue statement is just like break except that it won’t stop the execution of the loop. Instead, it just skips the current iteration to the next one. To be more clear, when the compiler encounters a continue statement, the rest of the statements in the loop body are skipped for that iteration, and it goes to the next iteration.

Consider the two code snippets:

labelx@ for (a in 1..5)
         for (b in 1..10) {
            if (b == 5)
                continue@labelx
            println(b)
        }
 for (a in 1..5)
         for (b in 1..10) {
            if (b == 5)
                continue
            println(b)
        }

In the first we’ve given a label to the outer loop. We are continuing the outer loop when b is 5. Thus the inner loop is terminated when the value is 5. It’s equivalent to adding a break statement, isn’t it?

In the second one, we added continue without any labels. So it just skips the succeding code when the condition b=5 is true.

That’s it for loops in Kotlin. If you think I’ve missed any important points, please let me know by adding a comment.

Exercises:

Loops is an important concept to understand clearly. You can find hundreds of loop exercise problems from the internet. You’ll have to practise doing many of them. I’m giving a few problems here. Please try them and if you encounter any difficulty while doing them, please feel free to ask me by dropping a comment.

Exercise

  • Write a program to find the sum of numbers till n.
  • Write a program to find the factorial of a number.
  • Write a program to generate this pattern of numbers (use nested loops)


1
12
123
1234
123345
123456
1234567

  • Write a program to generate the following pattern (nested loops)
kotlin loop exercise

« Back to the index of Kotlin tutorial

Add a Comment

Your email address will not be published. Required fields are marked *