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”
Kotlin Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
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) } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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 |