Introduction
A for loop with ranges helps you repeat actions a set number of times easily.
A for loop with ranges helps you repeat actions a set number of times easily.
for (i in start..end) { // code to repeat }
The start..end creates a range including both start and end.
You can use downTo to loop backward, and step to skip numbers.
for (i in 1..5) { println(i) }
for (i in 5 downTo 1) { println(i) }
for (i in 1..10 step 2) { println(i) }
This program shows three loops: counting up from 1 to 5, counting down from 5 to 1, and counting from 1 to 10 skipping by 3.
fun main() { println("Counting up:") for (i in 1..5) { println(i) } println("Counting down:") for (i in 5 downTo 1) { println(i) } println("Counting with steps:") for (i in 1..10 step 3) { println(i) } }
Ranges include the last number, so 1..5 means 1, 2, 3, 4, 5.
Use downTo to count backward.
Use step to jump numbers in the range.
For loops with ranges repeat code for numbers in a sequence.
You can count up, count down, and skip numbers using step.
This makes repeating tasks with numbers simple and clear.
for (i in 1..5) { println(i) }1..5 creates a range including numbers 1, 2, 3, 4, and 5.downTo to count down from a higher number to a lower number.5 downTo 1, which is correct. for (i in 5..1) { println(i) } uses an invalid range (5..1). for (i in 1..5 step -1) { println(i) } tries to use negative step incorrectly. for (i in 1 downTo 5) { println(i) } reverses the range incorrectly.var sum = 0
for (i in 1..5 step 2) {
sum += i
}
println(sum)for (i in 10..1 step 2) {
println(i)
}downTo instead of .., e.g., 10 downTo 1 step 2.2..20 step 2, which prints 2,4,6,...,20 correctly. for (i in 2..19) { if (i % 2 == 0) println(i) } ends at 19 so prints evens up to 18, missing 20. for (i in 2 downTo 20 step 2) { println(i) } counts down incorrectly. for (i in 1..10 step 2) { println(i * 2) } prints 2,6,10,..., not all even numbers.Pass the test and this pattern moves unknown