Kotlin for loop

In Kotlin, for loop is equivalent to foreach loop of other languages like C#. Here for loop is used to traverse through any data structure which provides an iterator. It is used very differently then the for loop of other programming languages like Java or C.

The syntax of for loop in Kotlin:

for(item in collection) {
       // code to execute
}

In Kotlin, for loop is used to iterate through the following because all of them provides iterator.

  • Range
  • Array
  • String
  • Collection

Iterate through range using for loop –

You can traverse through Range because it provides iterator. There are many ways you can iterate through Range. The in operator used in for loop to check value lies within the Range or not.
Below programs are example of traversing the range in different ways and in is the operator to check the value in the range. If value lies in between range then it returns true and prints the value.

  • Iterate through range to print the values:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>)
    {
        for (i in 1..6) {
            print("$i ")
        }
    }

    chevron_right

    
    

    Output:

    1 2 3 4 5 6
  • Iterate through range to jump using step-3 :
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>)
    {
        for (i in 1..10 step 3) {
            print("$i ")
        }
    }

    chevron_right

    
    

    Output:

    1 4 7 10
  • You can not iterate through Range from top to down without using DownTo :
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>)
    {
        for (i in 5..1) {
            print("$i ")
        }
        println("It prints nothing")
    }

    chevron_right

    
    

    Output:

    It prints nothing
  • Iterate through Range from top to down with using downTo :
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>)
    {
        for (i in 5 downTo 1) {
            print("$i ")
        }
    }

    chevron_right

    
    

    Output:

    5 4 3 2 1
  • Iterate through Range from top to down with using downTo and step 3:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>)
    {
        for (i in 10 downTo 1 step 3) {
            print("$i ")
        }
    }

    chevron_right

    
    

    Output:

    10 7 4 1
  • Iterate through array using for loop –

    An 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 you can traverse array:

    • Without using Index property
    • With Using Index property
    • Using withIndex Library Function
    • Traverse an array without using index property:
      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      fun main(args: Array<String>) {
          var numbers = arrayOf(1,2,3,4,5,6,7,8,9,10)
        
          for (num in numbers){
              if(num%2 == 0){
                  print("$num ")
              }
          }
      }

      chevron_right

      
      

      Output:

      2 4 6 8 10
    • Traverse an array with using index property:
      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      fun main(args: Array<String>) {
        
          var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn")
        
          for (i in planets.indices) {
              println(planets[i])
          }
      }

      chevron_right

      
      

      Output:

      Earth
      Mars
      Venus
      Jupiter
      Saturn
      
    • Traverse an array using withIndex() Library Function:
      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      fun main(args: Array<String>) {
          var planets = arrayOf("Earth", "Mars", "Venus", "Jupiter", "Saturn")
        
          for ((index,value) in planets.withIndex()) {
              println("Element at $index th index is $value")
          }
      }

      chevron_right

      
      

      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
      

    Iterate through string using for loop –

    A string can be traversed using the for loop because it also provides iterator.

    There are following ways to traverse the string:

    • Without using Index property
    • With Using Index property
    • Using withIndex Library Function
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>) {
        var name = "Geeks"
        var name2 = "forGeeks"
          
        // traversing string without using index property
        for (alphabet in name)   print("$alphabet ")
      
        // traversing string with using index property
        for (i in name2.indices) print(name2[i]+" ")
        println(" ")
          
        // traversing string using withIndex() library function
        for ((index,value) in name.withIndex())
        println("Element at $index th index is $value")
    }

    chevron_right

    
    

    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
    

    Iterate through collection using for loop –

    You can traverse the collection using the for loop. There are three types of collections list, map and set.
    In the listOf() function we can pass the different data types at the same time.

    Below is the program to traverse the list using for loop.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    fun main(args: Array<String>) {
      
        // read only, fix-size
        var collection = listOf(1,2,3,"listOf", "mapOf", "setOf")
      
        for (element in collection) {
            println(element)
        }
    }

    chevron_right

    
    

    Output:

    1
    2
    3
    listOf
    mapOf
    setOf
    


    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.