Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Using Ranges in Loops | Working with Ranges and Collections
Kotlin Loops

bookUsing Ranges in Loops

メニューを表示するにはスワイプしてください

What is a Range?

A range in Kotlin is a sequence of values between a start and an end. Ranges let you work with a continuous set of values, such as numbers or characters. You define a range using the .. operator, like 1..5, which represents the values from 1 to 5, inclusive. Ranges are commonly used in loops to simplify iterating over a series of values.

Main.kt

Main.kt

copy

Using Ranges in For Loops

You can use ranges in for loops to iterate over a sequence of values. In Kotlin, a range is defined using the .. operator for an inclusive range, which includes both the start and end values. To create an exclusive range (excluding the end value), use the until keyword.

  • Use start..end to include both the start and end values in the loop;
  • Use start until end to include the start value but exclude the end value;
  • Ranges can be used with any type that supports ordering, such as numbers and characters.

Example:

package com.example

fun main() {
    // Inclusive range: 1 to 5 (includes 5)
    for (i in 1..5) {
        println("Inclusive: $i")
    }
    // Exclusive range: 1 until 5 (does NOT include 5)
    for (j in 1 until 5) {
        println("Exclusive: $j")
    }
}

This code prints numbers from 1 to 5 for the inclusive range, and from 1 to 4 for the exclusive range. Using ranges makes your loops concise and easy to read.

Descending Ranges

You can loop backwards in Kotlin using the downTo keyword. This lets you create a range that starts from a higher number and goes down to a lower number, including both endpoints.

Syntax

for (i in 5 downTo 1) {
    println(i)
}

This loop prints the numbers from 5 down to 1, one per line.

Key Points

  • Use downTo to create a descending range;
  • Both start and end values are included in the loop;
  • You can use step with downTo to change the decrement value.

Example: Looping with Steps

for (i in 10 downTo 2 step 2) {
    println(i)
}

This prints 10, 8, 6, 4, and 2, showing how to count backwards by twos.

You learned how to create numeric and character ranges, use them with for loops, and combine them with collection operations for efficient data processing. Practicing these techniques will help you write cleaner and more expressive Kotlin code. Keep experimenting with different range scenarios to build your confidence and mastery.

question mark

Which of the following is the correct way to create a range for a for loop in Kotlin

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 2.  1
some-alt