Kotlin For Loop Example1 min read

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:


Leave a Comment