0
0
Kotlinprogramming~5 mins

For loop with ranges in Kotlin

Choose your learning style9 modes available
Introduction

A for loop with ranges helps you repeat actions a set number of times easily.

When you want to count from 1 to 10 and do something each time.
When you need to go through numbers between two values.
When you want to repeat a task a fixed number of times.
When you want to loop backward through numbers.
When you want to skip some numbers while looping.
Syntax
Kotlin
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.

Examples
This prints numbers from 1 to 5.
Kotlin
for (i in 1..5) {
    println(i)
}
This prints numbers 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: counting up from 1 to 5, counting down from 5 to 1, and counting from 1 to 10 skipping by 3.

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.

Use downTo to count backward.

Use step to jump numbers in the range.

Summary

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.