Kotlin for Loop

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

It is used to iterate a part of code several times. it iterate through array, collection(like list, map), ranges, String.

If body of for loop have only single statement we don’t need to use  curly braces {}.

Syntax

for(item in collection) {
       // this code executes
}

iterate through range using for loop : in is the operator to check the value in the range returns true if present.

fun main()
{
    for (i in 1..6) {
        print("$i ")
    }
}
Output
1 2 3 4 5 6 

we can not iterate using Range from top to down without using DownTo . let’s take an example

fun main()
{
    for (i in 6..1) {
        print("$i ")// it doesn't enter in this block
    }
    print("end")
}
output
end

example : in this program numbers decrements by 4

fun main()
{
    for(i in 15 downTo 1 step 4){
        print("$i ")
    }
}
output
15 11 7 3 

Iterate through array :

 // Traverse an array without using index property
fun main()
{
    var numbers = arrayOf(20,30,40,50,60)
    for(num in numbers){
        print("$num ")
    }
}
output:
20 30 40 50 60

Traverse an array using index property

fun main()
{
    var greeting = arrayOf("Hello", "Hola", "Hi")
    println(greeting.indices)// 0..2
    for(i in greeting.indices){
        println("greeting[$i] = ${greeting[i]}")
    }
}
output:
0..2
greeting[0] = Hello
greeting[1] = Hola
greeting[2] = Hi

Traverse an array using withIndex() Library Function

fun main()
{
    var colors = arrayOf("Green", "Blue", "Red","White")
    for((index, value) in colors.withIndex()){
        println("$index -> $value")
    }
}
output:
0 -> Green
1 -> Blue
2 -> Red
3 -> White

Iterate through String

Example 1 :

fun main()
{
    val name = "Coding Friction"
    for(alphabet in name)
       print("$alphabet ")
}
output
H e l l o

Example 2 :

fun main()
{
    val name = "Hello"
    println(name.indices)
    for( i in name.indices)
       println("name[$i] -> ${name[i]}")
}
Output
0..4
name[0] -> H
name[1] -> e
name[2] -> l
name[3] -> l
name[4] -> o

Iterate through list

fun main()
{
    var names = listOf("Kohli","Chris","AB") 
    for (name in names) { 
         print(name +" ") 
     }
} 
output:
Kohli Chris AB 

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe to get 15% discount