Kotlin – For Loop

Kotlin for loop is used to iterate a part of program several times. It iterates through arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C#.Syntax of for loop in Kotlin:

for (item in collection){
//body of loop
}

Iterate through arrayLet’s see a simple example of iterating the elements of array.

fun main(args : Array<String>) {
    val marks = arrayOf(80,85,60,90,70)
    for(item in marks){
        println(item)
    }
}

Output :

80
85
60
90
70

If the body of for loop contains only one single line of statement, it is not necessary to enclose within curly braces {}.

fun main(args : Array<String>) {
    val marks = arrayOf(80,85,60,90,70)
    for(item in marks)
        println(item)
}

The elements of an array are iterated on the basis of indices (index) of array. For example:

fun main(args : Array<String>) {
    val marks = arrayOf(80,85,60,90,70)
    for(item in marks.indices)
    println("marks[$item]: "+ marks[item])
}

Output :

marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70

Iterate through rangeLet’s see an example of iterating the elements of range.

fun main(args : Array<String>) {
    print("for (i in 1..5) print(i) = ")
    for (i in 1..5) print(i)
    println()
    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i) // prints nothing
    println()
    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)
    println()
    print("for (i in 5 downTo 2) print(i) = ")
    for (i in 5 downTo 2) print(i)
    println()
    print("for (i in 1..5 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)
    println()
    print("for (i in 5 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)
}

Output :

for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.