0
0
Kotlinprogramming~5 mins

Range operator (..) and in operator in Kotlin

Choose your learning style9 modes available
Introduction

The range operator (..) helps create a sequence of values easily. The in operator checks if a value is inside that sequence.

When you want to repeat an action a certain number of times.
When you want to check if a number falls between two limits.
When you want to loop through a list of numbers or characters.
When you want to verify if a value exists within a range.
When you want to simplify conditions that check for value boundaries.
Syntax
Kotlin
val range = start..end
if (value in range) {
    // do something
}

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

The in operator checks if a value is inside the range or collection.

Examples
This creates a range from 1 to 5 and prints the list [1, 2, 3, 4, 5].
Kotlin
val numbers = 1..5
println(numbers.toList())
This checks if the letter 'c' is inside the range from 'a' to 'd'. It prints true.
Kotlin
val letterRange = 'a'..'d'
println('c' in letterRange)
This loops from 1 to 3 and prints each number on its own line.
Kotlin
for (i in 1..3) {
    println(i)
}
Sample Program

This program checks if a score is within the passing range using the in operator. Then it prints numbers from 1 to 5 using the range operator in a loop.

Kotlin
fun main() {
    val score = 85
    val passingRange = 60..100

    if (score in passingRange) {
        println("You passed with a score of $score.")
    } else {
        println("You failed with a score of $score.")
    }

    println("Numbers from 1 to 5:")
    for (num in 1..5) {
        print("$num ")
    }
}
OutputSuccess
Important Notes

The range operator works with numbers and characters.

Ranges include both the start and end values.

You can use !in to check if a value is NOT in a range.

Summary

The .. operator creates a range of values.

The in operator checks if a value is inside that range.

Ranges are useful for loops and condition checks.