Kotlin for Loop

The for loop in Kotlin iterates through anything that provides an iterator. In this article, you learn to create for loop (with the help of examples).

Syntax

The syntax of for loop in Kotlin is:

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

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

  • Range
  • Array
  • String
  • Collection

Iterate through range using for loop

In Kotlin, the range is a collection of finite values which is defined by endpoints (start and stop).The start and stop are inclusive in the Range.

Given below are the examples of traversing the range in different ways:

Iterate through range to print the n values:
fun main(args: Array<String>)
{
//the loop iterates through the range and prints individual item.
for (i in 1..5) { 
     print("$i ") 
    } 
}
Output:
1 2 3 4 5
Iterate through range to print values only up to n-1 using until:
 for (i in 1 until 5) {
    print("$i ")
}
Output:
1 2 3 4

Iterate through range to jump using step :

In Kotlin, you can control the increment with step and the step value must be positive.

fun main(args: Array<String>)
{
  //increment the value of i by 2
    for (i in 1..10 step 2) {
        print("$i ")
    }
}
Output:
1 3 5 7 9
Iterate through Range from top to down using downTo:   
//Iterate through Range from top to down without using downTo 
//prints nothing

for (i in 10..1) {
    print("$i ")
}

Using downTo operator, gives you the expected result:

for (i in 10 downTo 1) {
    print("$i ")
}
Output:
10 9 8 7 6 5 4 3 2 1
Iterate through Range from top to down using downTo and step 3:
for (i in 10 downTo 1 step 3) {
    print("$i ")
}
Output:
10 7 4 1

Iterate through array using for loop 

An array is a collection of data of similar data type like Integer or String.

In an array, you can traverse in the following ways:

  • Without using Index property
  • Using Index property
  • Using withIndex() function

Traverse an array without using index property:
fun main(args: Array<String>) {

    var numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    for (num in numbers) {
        print("$num ")
    }
}
Output:
1 2 3 4 5 6 7 8 9 10

Traverse an array using index property:
fun main(args: Array<String>) {
   
    var days = arrayOf("Sunday", "Monday", "Tuesday", "wednesday", "Thursday", "Friday", "saturday")

    for (day in days.indices) {
        println(days[day])
    }
}
Output:
Sunday
Monday
Tuesday
wednesday
Thursday
Friday
saturday

Traverse an array using withIndex() function:
fun main(args: Array<String>) {
   
    var days = arrayOf("Sunday", "Monday", "Tuesday", "wednesday", "Thursday", "Friday", "saturday")

    for (day in days.withIndex()) {
        println("Item at ${day.index} index is  ${day.value}")
    }

    //OR
    /*for ((index,value) in days.withIndex()) {
        println("Item at $index index is  $value")*/
    }
Output:
Item at 0 index is Sunday
Item at 1 index is Monday
Item at 2 index is Tuesday
Item at 3 index is wednesday
Item at 4 index is Thursday
Item at 5 index is Friday
Item at 6 index is saturday

Iterate through string using for loop 

Strings are defined as an array of characters and is terminated with a special character ‘\0’.

These are the following ways to traverse the string:

  •  Without using index property:
  •  Using index property:
  •  Using withIndex() function:
package kotlinforloop

fun main(args: Array<String>) {

    var name = "C1C"
    var name2 = "TECH"
    var name3 = "C1CTECH"


    // traversing string without using index property
    for (i in name)
        print("$i ")


    // traversing string using index property
    for (i in name2.indices)
        print(name2[i] + " ")

    println()

    // traversing string using withIndex() function
    for ((index, value) in name3.withIndex())
        println("Item at $index index is $value")

    //OR
    /*for (data in name3.withIndex())
        println("Item at ${data.index} index is ${data.value}")*/

}

Output:
C 1 C T E C H 
Item at 0 index is C
Item at 1 index is 1
Item at 2 index is C
Item at 3 index is T
Item at 4 index is E
Item at 5 index is C
Item at 6 index is H

Iterate through collection using for loop

A collection usually contains a number of objects of the same type and these objects in the collection are called elements or items. You can traverse through collection (list, map, set) using the for loop.

In Kotlin, listOf() is used to create a list and we can pass different data types at the same time.

fun main(args: Array<String>) {
   //read only, fix-size
    var collection = listOf(1, 3.2, 9.9, "Donald", "Ankita", "Rohan")

    for (element in collection) {
        println(element)
    }

}
Output:
1
3.2
9.9
Donald
Ankita
Rohan

 

Leave a Reply