Signup/Sign In

Kotlin for Loop

In this tutorial, we will discuss about for loop in Kotlin. There is no traditional for loop in Kotlin unlike C, C++, Java etc., which will execute until a condition returns false. The for loop in Kotlin is similar to forEach loop in Java.

The for loop is used to iterate over any Kotlin object which can be iterated. We can iterate over an array, collection, string, range, or anything which can be iterated with the help of a for loop.

Kotlin for Loop

Here is the syntax of for loop:

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

Here the item is the variable in which values will be stored for every loop execution and the collection is the Kotlin object on which we are iterating.

The for loop in Kotlin is not used for performing operations, again and again, rather it is used to iterate over any Kotlin object like an array, list, or any collection object to perform some operation using their elements.

Kotlin for Loop Example

Let us see an example in which we will iterate over an array of marks in Kotlin:

fun main() {
    val marks: Array<Int> = arrayOf(9,8,3,10,7,9)
    for (subjectScore in marks){
        println(subjectScore)
    }
}


9
8
3
10
7
9

Here, the for loop will continue to execute until all the elements present in the array are covered. If a single line is present in the body of the loop, the curly braces can be removed.

We can also use the index of the iterable item to iterate over it:

fun main() {
    val marks: Array<Int> = arrayOf(9,8,3,10,7,9)
    for (index in marks.indices)
        println("Score in subject $index is: " + marks[index])
}


Score in subject 0 is: 9
Score in subject 1 is: 8
Score in subject 2 is: 3
Score in subject 3 is: 10
Score in subject 4 is: 7
Score in subject 5 is: 9

Iterate over Kotlin string:

In the below example, we will iterate over characters of a string:

fun main() {
    val name = "Ninja"
    for (alphabet in name){
        println(alphabet)
    }
}


N
i
n
j
a

Summary

In this tutorial, we covered the for loop in Kotlin. In the next tutorial, we will discuss about range in Kotlin and how we can use range in Kotlin loops.



About the author:
I'm a writer at studytonight.com.