Kotlin Tutorial menu

Kotlin Loops, Ranges and Collections

Loops repeat code, and collections hold many values in one variable.

while and do-while

A while loop runs as long as its condition is true:

Example

kotlin
fun main() {
    var count = 1
    while (count <= 3) {
        println("Count: $count")
        count++
    }
}
Output
Count: 1
Count: 2
Count: 3

A do-while loop runs the code once first, then checks the condition. Use it when the code must run at least one time.

for Loops and Ranges

A range like 1..5 means 1, 2, 3, 4 and 5. The for loop goes through each value:

Example

kotlin
fun main() {
    for (i in 1..5) print("$i ")
    println()
    for (i in 1..10 step 3) print("$i ")
    println()
    for (i in 5 downTo 1) print("$i ")
    println()
    for (i in 0 until 4) print("$i ")
    println()
}
Output
1 2 3 4 5 
1 4 7 10 
5 4 3 2 1 
0 1 2 3 
RangeValues
1..51 to 5, including 5
0 until 40 to 3 (4 is not included)
5 downTo 1counts backwards
1..10 step 3jumps 3 at a time

break and continue

  • break stops the loop completely.
  • continue skips the rest of this round and moves to the next one.

Example

kotlin
fun main() {
    for (i in 1..10) {
        if (i == 3) continue
        if (i == 6) break
        println(i)
    }
}
Output
1
2
4
5

Lists

A List keeps values in order. listOf() makes a read-only list. mutableListOf() makes one you can change.

Example

kotlin
fun main() {
    val fruits = listOf("Mango", "Apple", "Banana")
    println(fruits[0])
    println(fruits.size)

    for (fruit in fruits) {
        println("I like $fruit")
    }

    val cart = mutableListOf("Rice", "Sugar")
    cart.add("Tea")
    cart.remove("Sugar")
    println(cart)
}
Output
Mango
3
I like Mango
I like Apple
I like Banana
[Rice, Tea]

Positions (indexes) start at 0, so fruits[0] is the first item.

Arrays

An array has a fixed size. Create one with arrayOf():

Example

kotlin
fun main() {
    val marks = arrayOf(70, 85, 92)
    marks[0] = 75
    println(marks.sum())
    println(marks.joinToString())
}
Output
252
75, 85, 92

In everyday Kotlin, lists are used much more than arrays. Choose a list unless you have a special reason.

Sets and Maps

  • A Set holds values with no duplicates.
  • A Map holds key to value pairs, like a name and its marks.

Example

kotlin
fun main() {
    val colours = setOf("red", "green", "red", "blue")
    println(colours)

    val results = mapOf("Ali" to 85, "Ayesha" to 92)
    println(results["Ayesha"])
    for ((name, marks) in results) {
        println("$name scored $marks")
    }

    val stock = mutableMapOf("Pen" to 20)
    stock["Notebook"] = 15
    println(stock)
}
Output
[red, green, blue]
92
Ali scored 85
Ayesha scored 92
{Pen=20, Notebook=15}

Exercise

Exercise

Which values does the loop for (i in 0 until 3) go through?

Learn Kotlin with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp