Kotlin For Loops & Usage Examples | Android Introduction #14
In this reading, you will learn how to use the for-loop with numbers.
Let’s review the most important use cases for using for-loops with numbers.
To call code for each number from a to b, including b, use the range a..b inside a for-loop. The following code block should print the numbers 0, 1, 2, 3, 4 and 5.
fun main() {
val a = 0
val b = 5
for (i in a..b) {
println(i)
}
}
To call code for each number from a to b, excluding b, use a range a until b inside a for-loop. The following code block should print the numbers 0, 1, 2, 3 and 4.
fun main() {
val a = 0
val b = 5
for (i in a until b) {
println(i)
}
}
To call code for each number from a to b, where a is bigger than b, and the step should be -1, use a downTo b inside a for-loop. The below code should print the numbers 5, 4, 3, 2, 1 and 0.
fun main() {
val a = 5
val b = 0
for (i in a downTo b) {
println(i)
}
}
To call code for each number from a to b, with a step c, use a..b step c inside a for-loop. The code below should print the numbers 0, 3, 6 and 9.
fun main() {
val a = 0
val b = 10
val c = 3
for (i in a..b step c) {
println(i)
}
}
To call code for each number from a to b, excluding b, with a step c, use a until b step c inside a for-loop. The below code should print the numbers 0, 3 and 6.
fun main() {
val a = 0
val b = 9
val c = 3
for (i in a until b step c) {
println(i)
}
}
To call code for each number from a to b, where a is bigger than b, with a step -c, use a downTo b step c inside a for-loop. The below code should print the numbers 10, 7, 4 and 1.
Note: in kotlin, The step accepts only positive numbers even in case using downTo .
fun main() {
val a = 10
val b = 1
val c = 3
for (i in a downTo b step c) {
println(i)
}
}
You can use this to generate the text for a silly song. Start the code below to find out what it’s going to print.
fun main() {
for (num in 5 downTo 1) {
println("$num lemonades are left")
println("Glupglupglup")
}
println("That is it")
println("Now I have to go")
}
In this reading, you learned how to use the for-loop with numbers.