![]() |
VOOZH | about |
In Kotlin, the for loop is equivalent to the foreach loop of other languages like C#. Here for loop is used to traverse through any data structure that provides an iterator. It is used very differently then the for loop of other programming languages like Java or C. The syntax of the for loop in Kotlin:
for(item in collection) {
// code to execute
}
In Kotlin, a for loop is used to iterate through the following because all of them provide an iterator.
Table of Content
You can traverse through the Range because it provides an iterator. There are many ways you can iterate through a Range. The 'in' operator is used in a for loop to check value lies within the Range or not. The following programs are examples of traversing the range in different ways, and 'in' is the operator to check the value in the range. If the value lies between the range, then it returns true and prints the value.
Output
1 2 3 4 5 6
Output
1 4 7 10
Output
It prints nothing
Output
5 4 3 2 1Iterate through the Range from top to down with using downTo and step 3:
Output
10 7 4 1An array is a data structure which contains same data type like Integer or String. Array can be traversed using for loop because it also provides iterator. Each array has a starting index and by default, it is 0.
There are the following can traverse the array:
Output
2 4 6 8 10
Output
Earth
Mars
Venus
Jupiter
Saturn
withIndex() Library Function
Output
Element at 0 th index is Earth
Element at 1 th index is Mars
Element at 2 th index is Venus
Element at 3 th index is Jupiter
Element at 4 th index is Saturn
A string can be traversed using the for loop because it also provides an iterator.
There are the following ways to traverse the string:
Output
G e e k s f o r G e e k s
Element at 0 th index is G
Element at 1 th index is e
Element at 2 th index is e
Element at 3 th index is k
Element at 4 th index is s
You can traverse the collection using a for loop. There are three types of collections: list, map, and set. In the listOf() We can pass the different data types at the same time.
Below is the program to traverse the list using a for loop.
Output
1
2
3
listOf
mapOf
setOf