3 minutes read

Sometimes, you need to repeat a group of statements several times. You can just copy-paste the expression. What if you want to repeat it one hundred thousand times? Copy-paste is clumsy in this case.

Fortunately for us, Kotlin provides several special statements to repeat blocks of code multiple times. These statements are known as loops. They are useful when it comes to repeating multiple statements.

Repeat loop

To use the simplest loop, write repeat(n) and a sequence of statements in curly braces {...}. n is an integer that determines how many times these statements are going to be repeated.

repeat(n) {
    // statements
}

For example, the program below prints Hello three times:

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

Output:

Hello
Hello
Hello

Tip: If n is zero or a negative number, Kotlin will ignore the loop. If n is one, the statements will be executed only once.

Kotlin has the opportunity to control the current iteration with the it name:

fun main() {
    repeat(3) {
        println(it)
    }
}

Output:

0
1
2

The code in curly braces is commonly called a "lambda expression". It's a function that doesn't have a name and is passed immediately as an expression. You can find more information about lambdas here.

Reading and processing data in a loop

You can read data from the standard input, declare variables and even perform calculations inside the repeat statement.

Take a look at this example. The program below reads numbers from the standard input and calculates their sum. The first number is not a part of the sum, it determines the length of the input sequence.

fun main() {    
    val n = readln().toInt()
    var sum = 0
    
    repeat(n) {
        val next = readln().toInt()
        sum += next
    }
    
    println(sum)
}

This code reads a length of a number sequence and assigns it to the n variable. After that, it creates a variable to store the total sum. The code reads the next number and adds it to the sum exactly n times. Then, the loop stops, and the program prints the total sum.

Here is an example of input numbers:

5
40
15
30
25
50

Output:

160

Conclusion

Loops are useful when you need to repeat a statement in your code. In this topic, we have discussed the repeat() loop. It is a very simple tool. Define the number of executions, then the statement in curly braces, and off you go! In the next lesson, we will learn about advanced loops and how they can be applied to more complex issues.

1115 learners liked this piece of theory. 14 didn't like it. What about you?
Report a typo