Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn skotlin Ranges


Ranges in Kotlin represent a sequence of values from a start value to an end value. They are often used in loops and conditional statements. Here's a simple explanation with examples:

Creating Ranges

You can create a range using the .. operator.

Example

val numbers = 1..5 // Range from 1 to 5 (inclusive)

Range with Step

You can also specify a step value to create a range with a specific interval between values.

Example

val evenNumbers = 2..10 step 2 // Range of even numbers from 2 to 10

Iterating Over a Range

Ranges are commonly used in loops to iterate over a sequence of values.

Example

for (number in 1..5) {
println(number)
}

OutPut

1
2
3
4
5
6

Checking Range Membership

You can use the in operator to check if a value is within a range.

Example

val x = 3
val isInRange = x in 1..5 // true

Reversing a Range

You can reverse a range using the reversed() function.

Example

val reversedRange = (5 downTo 1) // Range from 5 to 1 in reverse order

Checking Range Emptiness

You can check if a range is empty using the isEmpty() function.

Example

val emptyRange = 10..5 // Empty range
val isEmpty = emptyRange.isEmpty() // true

Conclusion

Ranges in Kotlin provide a convenient way to represent sequences of values. They are versatile and can be used in various scenarios, including looping, checking membership, reversing, and checking for emptiness. Understanding and utilizing ranges can simplify many programming tasks in Kotlin.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java