Kotlin For Loop

Chapter: Kotlin Last Updated: 30-11-2017 07:43:24 UTC

Program:

            /* ............... START ............... */
                
fun main(args: Array<String>) {

    // Basic for loop in Kotlin

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

    print("for (i in 5..1) print(i) = ")
    for (i in 5..1) print(i)             // prints nothing

    println()

    print("for (i in 5 downTo 1) print(i) = ")
    for (i in 5 downTo 1) print(i)

    println()

    print("for (i in 1..4 step 2) print(i) = ")
    for (i in 1..5 step 2) print(i)

    println()

    print("for (i in 4 downTo 1 step 2) print(i) = ")
    for (i in 5 downTo 1 step 2) print(i)

    // Kotlin for loop iterate through an array.

    println()

    var language = arrayOf("C#", "Koltin", "Python","Java")

    for (item in language)
        println(item)

}
                /* ............... END ............... */
        

Output

1
2
3
4
5
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 1..4 step 2) print(i) = 135
for (i in 4 downTo 1 step 2) print(i) = 531
C#
Koltin
Python
Java

Notes:

  • For loop in Kotlin is slightly different from java. In Kotlin, for loop is used to iterate through ranges, arrays and maps.
  • First go through the program given above and understand the flow of for loop in Kotlin.
  • Range expressions are formed with rangeTo functions that have the operator form, which is complemented by in and !in. Range is defined for any comparable type, but for integral primitive types it has an optimized implementation. Here are some examples of using ranges:
  • if (i in 1..10) -- equivalent of 1 <= i && i <= 10
  • for (i in 1..4) print(i) -- prints "1234"
  • for (i in 4..1) print(i) -- prints nothing
  • for (i in 4 downTo 1) print(i) -- prints "4321"
  • for (i in 1..4 step 2) print(i) -- prints "13"
Similar Programs Chapter Last Updated
Kotlin Continue Kotlin 02-03-2018
Kotlin Break Statement Kotlin 27-01-2018
Kotlin Do While Loop Kotlin 19-11-2017
Kotlin While Loop Kotlin 19-11-2017
Kotlin When Statement Kotlin 18-11-2017
Kotlin Nested If Kotlin 18-11-2017
Kotlin If Else If Statement Kotlin 22-09-2018
Kotlin If Statement Kotlin 17-11-2017
Kotlin Print And Println Kotlin 22-09-2018
Kotlin Type Conversion Kotlin 17-11-2017
Kotlin Logical Operators Kotlin 17-11-2017
Kotlin Assignment Operators Kotlin 15-11-2017
Kotlin Arithmetic Operators Kotlin 15-11-2017
Kotlin Data Types Kotlin 12-11-2017
Kotlin Variables Example Kotlin 11-11-2017
Kotlin Comments Example Kotlin 11-11-2017
Kotlin Hello World Kotlin 11-11-2017

1