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"
Tags
For Loop , Kotlin, For Loop range