What are loops in Kotlin?

We use loops in Kotlin when we want to perform an action repetitively. Loops help make our code more organized and manageable.

Kotlin supports three types of loops:

  1. The while loop
  2. The do-while loop
  3. The for loop

The while loop

The while loop executes a block of code repeatedly, as long as the specified condition is true. When the condition becomes false, the loop terminates.

If the condition is false at the start of the loop, it does not execute the code.

Syntax

while (condition) {
// Body
}
Syntax of thewhile loop

Example

In the following code widget, we see the use of the while loop in Kotlin:

fun main(args : Array<String>) {
// Declaring a variable
var i: Int = 0
// Using the while loop
while (i < 5) {
i++
}
// Printing i on the console
println(i)
}
do {
// Body
} while (condition);
Syntax of the do-while loop
fun main(args : Array<String>) {
// Declaring a variable
var i: Int = 0
// Using the do-while loop
do {
i++
} while (i < 5)
// Printing i on the console
println(i)
}
for (item in collection) {
// Body
}
Syntax of the for loop
fun main(args : Array<String>) {
// Declaring a collection
var numbers = arrayOf<Int>(1, 2, 3, 4)
// Using the for loop
for (num: Int in numbers) {
// Printing num on the console
println(num)
}
}

Free Resources