To repeatedly execute a code block multiple times, we use loops. The most basic loop in Kotlin is the repeat
statement. We just have to write the number of times a code block needs to be executed. Syntax :
repeat (/* no. of times */) {
// Code
}
Following code prints Hello World!
3 times :
fun main() {
repeat (3) {
println("Hello World!")
}
}
We can also access the loop variable i.e. iteration number (0 -> 2)
using the it
variable :
fun main() {
repeat (3) {
println("$it. Hello World!")
}
}
/* Output :
0. Hello World!
1. Hello World!
2. Hello World!
*/
repeat statements loop variable always starts from 0
and ends at n-1
. If we need more customizable range, we can use for loops.