Lesson 7 / 25
Loops and ranges
Explain Loops and ranges, run a focused example, and inspect the result.
The essential idea
Loops and ranges makes a Kotlin program more expressive while keeping the code readable. Identify the value, the rule, and the result before you try to remember the syntax.
Trace the loop
Read top to bottom, then run the code and use its output as evidence.
var sum = 0
for (n in 1..3) {
sum += n
}
println(sum)
Output:
6
- Line 1: The accumulator starts before the range yields a value.
- Line 2: The inclusive range gives 1 first.
- Line 3: The body updates the running total.
- Line 5: The range ends after 3 and the final total prints.
A practical habit
For Loops and ranges, run a very small example and change only one part. The compiler and output will show whether your explanation is correct.
Quick check
Quick check: How should you practise Loops and ranges?
- Run a focused small program.
- Memorize without compiling.
- Ignore errors.
Answer
Run a focused small program. — Small experiments make cause and effect visible.