0
0
Kotlinprogramming~5 mins

Why ranges simplify iteration in Kotlin

Choose your learning style9 modes available
Introduction

Ranges let you easily repeat actions for a set of numbers without writing extra code. They make loops simple and clear.

When you want to count from 1 to 10 and do something each time.
When you need to check every number between two values.
When you want to run a loop a fixed number of times.
When you want to create a list of numbers quickly.
When you want to step through numbers with a specific gap, like every 2 or 3.
Syntax
Kotlin
for (i in start..end) {
    // code to repeat
}

The .. operator creates a range from start to end, including both.

You can use downTo to count backwards, and step to skip numbers.

Examples
This prints numbers 1 to 5, one per line.
Kotlin
for (i in 1..5) {
    println(i)
}
This counts backwards from 5 down to 1.
Kotlin
for (i in 5 downTo 1) {
    println(i)
}
This prints every second number from 1 to 10: 1, 3, 5, 7, 9.
Kotlin
for (i in 1..10 step 2) {
    println(i)
}
Sample Program

This program shows three loops using ranges: counting up, counting down, and counting with steps.

Kotlin
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)
    }
}
OutputSuccess
Important Notes

Ranges include the last number, so 1..5 means 1, 2, 3, 4, 5.

You can use ranges with other types like characters, for example 'a'..'e'.

Using ranges makes your code shorter and easier to read compared to manual loops.

Summary

Ranges let you loop over numbers easily and clearly.

You can count up, down, or skip numbers with ranges.

Using ranges makes your code simpler and less error-prone.