Beginner: Kotlin · Kotlin basics · topic 4 of 50 · 25 min
Loops and ranges
Explanation
Why loops?
Many jobs repeat: print a bill line for each item, send a reminder to every student, try an OTP up to three times. A loop runs a block of code again and again, so you write it once. Each run is called an iteration.
Ranges
A range is a sequence of values from a start to an end. Kotlin has several ways to write one:
| Range | Values | Notes |
|---|---|---|
| 1..5 | 1, 2, 3, 4, 5 | Both ends included |
| 1 until 5 or 1..<5 | 1, 2, 3, 4 | End excluded; handy for list positions |
| 5 downTo 1 | 5, 4, 3, 2, 1 | Counting down |
| 1..10 step 3 | 1, 4, 7, 10 | Skip by 3 |
| 'a'..'e' | a, b, c, d, e | Ranges of characters work too |
for loops
fun main() {
for (i in 1..3) {
println("Round $i")
}
for (i in 10 downTo 0 step 5) {
print("$i ") // 10 5 0
}
println()
val cities = listOf("Delhi", "Agra", "Jaipur")
for (city in cities) {
println("Tour stop: $city")
}
for ((index, city) in cities.withIndex()) {
println("${index + 1}. $city")
}
}Most of the time in real apps you loop over a collection directly (for (city in cities)) rather than over numbers. Use a numeric range only when you really need the numbers, such as a table or a countdown.
while and do-while
while checks its condition before each round; if it is false at the start, the body never runs. do-while checks after, so the body always runs at least once, which suits "ask, then check" situations.
fun main() {
var balance = 1000
var months = 0
while (balance > 0) {
balance -= 300 // monthly EMI
months++
}
println("Paid off in $months months") // 4
var attempts = 0
do {
attempts++
println("Attempt $attempts")
} while (attempts < 2)
}repeat
repeat(3) {
println("Reminder: pay your electricity bill")
}break and continue
fun main() {
for (n in 1..10) {
if (n % 2 == 0) continue // skip even numbers
if (n > 7) break // stop the loop
print("$n ") // 1 3 5 7
}
}With nested loops, break and continue affect only the innermost loop. To leave an outer loop, Kotlin lets you add a label like outer@ and write break@outer. Use this sparingly; often a function with return is clearer.
Common mistakes
- Using 0..list.size to loop over positions: the last value equals size, which is past the end and crashes. Use 0 until list.size, list.indices, or loop over the items directly.
- A while loop whose condition never becomes false: an endless loop. Make sure something inside changes the condition.
- Writing 5..1 to count down: it is an empty range. Use 5 downTo 1.
- Changing a val counter inside a loop. Counters must be var.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Loops and ranges · 1/6
Loops repeat code so you write it once. Each repeat is an iteration.
Prefer a video by a teacher? Find free videos on “kotlin for loop while ranges until downTo step” on YouTube ↗
In real life: A multiplication table for a school app
A learning app for primary school children shows multiplication tables. One for loop over 1..10 builds each line with a string template. When a child picks a different number, the same loop prints a new table.
fun main() {
val n = 7
for (i in 1..10) {
println("$n x $i = ${n * i}")
}
}Practice (0/3 done)
What does this print? for (i in 1..10 step 4) print("$i ")
How many times does the body run? var n = 10 while (n < 5) { n++ }
Write a program that (1) prints the 13 times table with for, (2) counts down from 10 to 1 with downTo and prints "Lift off!", (3) uses a while loop to find how many years it takes Rs 10,000 at 8% yearly interest to double, and (4) prints only the odd numbers from 1 to 20 using continue.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- First program, val and var, and typesKotlin basics · same module
- Kotlin and Android: the big pictureKotlin basics · same module
- Loops: for, while, do-while and range-forC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- Loops: repeating workFrontend Web Development · JavaScript basics
- Control flow: if, loop, while and forRust Programming · Types, control flow and functions
- Loops: for, while, do…while, for…of and for…inJavaScript Programming (language in depth) · Strings, decisions and loops
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which range gives 0, 1, 2, 3?
Answer: 0 until 4
until excludes the end value.
Which loop always runs its body at least once?
Answer: do-while
do-while checks the condition after the body.
What does continue do?
Answer: Skips the rest of this round and starts the next
continue moves to the next iteration.
What does 5..1 contain?
Answer: Nothing: it is an empty range
Use 5 downTo 1 to count down.
Which loop always runs its body at least once?Related
Answer: do-while
do-while checks its condition after the body.
Which loop is best to visit every item of an array?Related
Answer: for...of
for...of gives you each item in turn, with no index to manage.
What is special about loop compared to while?Related
Answer: It can return a value with break value
loop can hand a value out with break, which makes it an expression.
Which loop always runs its body at least once?Related
Answer: do…while
do…while checks the condition after the first run.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Kotlin basics”. The module exam comes next.
- Module 1 exam: Kotlin basics · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Null safety, functions and lambdas. 50 topics left in the course before the final exam.