Range Operator (..) in Kotlin
On this page (8sections)
Definition
- This operator is used to mention a range of values inclusive of the from and to values.
- It is represented by ”..”
- This operator can be used only in the increasing order of ranges.
- Range operators are mainly used along with in and !in operators.
- While using range operator for iterating through a range, it is possible to set a range even skipping values. This is done using “step” keyword.
Syntax
1. Normal Usage
from_value .. to_value
For example,
if(4 in 1..10){
//This will get printed while iterating through values : 1,2,3,4,5,6,7,8,9 and 10
println("The value is in the range")
}
2. Range Operator with “step” Usage
from_value .. to_value step skip_value
For example,
if(4 in 1..10 step 4){
//This will get printed while iterating through values 1,4 and 8 skipping 4 values starting from 1 until 10.
println("The value is in the range")
}
Range Operator Example Program in Kotlin
//Range Operator Example Program in Kotlin
//Operator Kotlin Programs, Basic Kotlin Program
fun main(args: Array<String>) {
println("Loop 1")
//Printing values in range 100 to 105
for(num in 100..105){
println("$num is in the range")
}
println("\nLoop 2")
//Printing values in range 100 to 105 skipping 2 values
for(num in 100..105 step 2){
println("$num is in the range")
}
}
Sample Output
Loop 1
100 is in the range
101 is in the range
102 is in the range
103 is in the range
104 is in the range
105 is in the range
Loop 2
100 is in the range
102 is in the range
104 is in the range
How It Works
This Kotlin program demonstrates Range Operator (..). It first prepares the data it needs, then walks through the data with a loop to compute the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Iterate over the data using a loop to apply the logic.
- Use conditional statements to handle the different cases.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Range Operator (..) in Kotlin?
This operator is used to mention a range of values inclusive of the from and to values.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Range Operator (..)?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.