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
fun main() {
var count = 1
while (count <= 3) {
println("Count: $count")
count++
}
}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
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()
}1 2 3 4 5 1 4 7 10 5 4 3 2 1 0 1 2 3
| Range | Values |
|---|---|
1..5 | 1 to 5, including 5 |
0 until 4 | 0 to 3 (4 is not included) |
5 downTo 1 | counts backwards |
1..10 step 3 | jumps 3 at a time |
break and continue
breakstops the loop completely.continueskips the rest of this round and moves to the next one.
Example
fun main() {
for (i in 1..10) {
if (i == 3) continue
if (i == 6) break
println(i)
}
}1 2 4 5
Lists
A List keeps values in order. listOf() makes a read-only list. mutableListOf() makes one you can change.
Example
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)
}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
fun main() {
val marks = arrayOf(70, 85, 92)
marks[0] = 75
println(marks.sum())
println(marks.joinToString())
}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
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)
}[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?
