Loops
Sometimes, you need to repeat a group of statements several times. You can just copy-paste these statement in your code. But if you want to repeat something one hundred thousand times or an unknown number of times (before the start of your program), this approach will not help you.
Fortunately, Kotlin provides several special statements to repeat a block of code multiple times. These statements are known as loops. To solve a problem that needs repetitions, you should choose the most suitable loop and then correctly apply it to your problem.
The repeat loop
repeat(n)
and a sequence of statements to be executed in curly braces {...}
. The value n
is an integer number that determines how many times these statements have to be repeated.repeat(n) {
// statements
}
As an example, the following program prints "Hello" exactly three times.
fun main(args: Array<String>) {
repeat(3) {
println("Hello")
}
}
Hello
Hello
Hello
n
is less or equal zero, the loop will be ignored. If n
is one, all statements will be executed only once like no loops here.Reading and processing data in a loop
Inside the curly braces of repeat
, you can read data from the standard input, declare variables and even perform calculations.
As a complex example, the following program reads numbers from the standard input and calculates their sum. We assumed, the first number is not a part of the sum, it determines the length of the input sequence.
import java.util.*
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val n = scanner.nextInt()
var sum = 0
repeat(n) {
val next = scanner.nextInt()
sum += next
}
println(sum)
}
This code reads a length of the number's sequence and assigns it to the variable n
. It creates a variable to store an accumulated sum. This code read the next number and adds it to the sum exactly n
times. After this loop stops, the program prints the accumulated sum.
Here is an example of input numbers:
5
40
15
30
25
50
The output is:
160
Of course, this program is simple enough but it demonstrates the key aspects of any loops in programs. In the next lesson, we will learn some advanced loops and apply them to solve more complex problems.