Profile
March 3, 2023

Ways to use loops in Kotlin with examples: For, While, Do-while, Repeat, Foreach Loop in Kotlin

Learn how to use loops in Kotlin with examples of popular loop structures like for, while, do-while, repeat, and foreach loop.

For loop:

The for loop iterates over a range of values, arrays, or any other iterable object.

Example:

for (i in 1..5) {
    println(i)
}
// output 
// 1
// 2
// 3
// 4
// 5

 

for loop with the until keyword. The until keyword is used to create a range that excludes the upper bound.

Example:

for (i in 1 until 5) {
    println(i)
}
// output 
// 1
// 2
// 3
// 4

This loop will iterate from 1 to 4 (inclusive of 1 and exclusive of 5). You can also specify a step value using the step keyword:

for (i in 1 until 10 step 2) {
    println(i)
}
// output 
// 1
// 3
// 5
// 7
// 9

This loop will iterate from 1 to 9 with a step of 2 (i.e., it will print 1, 3, 5, 7, and 9).

 

While loop:

The while loop iterates while the condition is true.

Example:

var i = 1
while (i <= 5) {
    println(i)
    i++
}
// output 
// 1
// 2
// 3
// 4
// 5

 

do-while loop:

The do-while loop iterates at least once and then check the condition.

Example:

var i = 1
do {
    println(i)
    i++
} while (i <= 5)

// output 
// 1
// 2
// 3
// 4
// 5

 

ForEach loop:

The forEach loop iterates over each element of an array or a collection.

Example:

val numbers = arrayOf(1, 2, 3, 4, 5)
numbers.forEach {
    println(it)
}
// output 
// 1
// 2
// 3
// 4
// 5

 

Repeat loop:

The repeat loop repeats the block of code a specified number of times.

Example:

repeat(5) {
    println("Hello")
}
//output
// Hello
// Hello
// Hello
// Hello
// Hello

These are the five main ways to create a loop in Kotlin.

Last edited on August 6, 2023 by Admin

Latest articles