Kotlin For Loop

Kotlin , for loop iterates through anything that provides an iterator. This is equivalent to the foreach loop in languages like java. 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#.

  The syntax is as follows:

for (item in collection) 
          print(item)
The body can be a block.
for (item: Int in ints) {
    // ...
}


Iterate through array


 fun main(array: Array) {
 
     var names = arrayOf("Roshni","Durgesh", "Amit", "Ravi", "Vicky", "Ravi")
 
 
 
     for (name in names) {
         println("Hello ${name} your name length is ${name.length}")
     }
 
 }
Hello Roshni your name length is 6
 Hello Durgesh your name length is 7
 Hello Amit your name length is 4
 Hello Ravi your name length is 4
 Hello Vicky your name length is 5
 Hello Ravi your name length is 4
 

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

fun main(array: Array) {

    var numbers = 1..5

    for (i in numbers)
        println(i)


}
1
2
3
4
5

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


fun main(array: Array) {

    var numbers = arrayOf(45, 65, 67, 76, 5, 676)

    for (i in numbers.indices) {
        println("Index ${i}")
        println("Element ${numbers[i]}")
        println("---------------")
    }


}
Index 0
Element 45
---------------
Index 1
Element 65
---------------
Index 2
Element 67
---------------
Index 3
Element 76
---------------
Index 4
Element 5
---------------
Index 5
Element 676
---------------

Reverse Loop printing numbers 5 to 1

fun main(array: Array) {


    for(i in 5 downTo 1 )
    {
        println(i)
    }


}
5
4
3
2
1

If you want to iterate through an array or a list with an index, you can use the withIndex library function:


fun main(array: Array) {


    var nums = arrayOf(34, 54, 67, 65)

    for ((index, value) in nums.withIndex()) {
        println("Index : ${index} - Value : ${value}");
    }


}
Index : 0 - Value : 34
Index : 1 - Value : 54
Index : 2 - Value : 67
Index : 3 - Value : 65
woman avatar