ELEVATE YOUR BUSINESS WITH

Limitless customization options & Elementor compatibility let anyone create a beautiful website with Valiance.

Ranges in Kotlin

SELECT * FROM `itio_tutorial_master` WHERE `tutorial_menu`='25' AND `tutorial_submenu`='78' AND `tutorial_status`=1 LIMIT 1

Ranges in Kotlin

πŸ“Œ Ranges in Kotlin

In Kotlin, a Range represents a sequence of values defined between a start and an end value. Ranges are commonly used for looping or checking if a value falls within a specific range.


βœ… Creating Ranges in Kotlin

You can create ranges using the .. operator, until, or downTo.

πŸ“Œ 1. Using .. Operator (Inclusive)

  • The .. operator includes both start and end values.

kotlin

range = 1..5println(range.toList()) // Output: [1, 2, 3, 4, 5]


πŸ“Œ 2. Using until Operator (Exclusive)

  • Excludes the end value.

kotlin

val range = 1 until 5println(range.toList()) // Output: [1, 2, 3, 4]

  • until is useful when you don’t want to include the last number.


πŸ“Œ 3. Using downTo Operator

  • Creates a range in descending order.

kotlin

val range = 5 downTo 1println(range.toList()) // Output: [5, 4, 3, 2, 1]


πŸ“Œ 4. Using step with Ranges

  • You can specify steps to skip values.

kotlin

val range = 1..10 step 2println(range.toList()) // Output: [1, 3, 5, 7, 9]

  • step is useful when you need to iterate by a certain increment.


βœ… Using Ranges in Control Structures

πŸ“Œ 1. Using in to Check Membership

You can check if a number exists within a range using in or !in.

kotlin

val number = 8if (number in1..10) { println("$number is within the range.")} { println("$number is out of the range.")}

Output:

pgsql

8iswithin the range.


πŸ“Œ 2. Using Ranges in For Loops

kotlin

for (i in1..5) { println(i)}

Output:

12345

  • Descending with Step:

kotlin

for (i in10 downTo 1 step 2) { println(i)}

Output:

108642


βœ… Character and String Ranges

Kotlin supports character ranges using ...

kotlin

val charRange = 'a'..'e'println(charRange.toList()) // Output: [a, b, c, d, e]

You can also check if a character exists within a range:

kotlin

val letter = 'c'println(letter in'a'..'z') // Output: true


βœ… Conclusion

  • Use .. for inclusive ranges.

  • Use until for exclusive ranges.

  • Use downTo for reverse ranges.

  • Use step to customize increments.

  • Use in and !in for membership checks.

  • Ranges work with numbers, characters, and loops.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql