Ranges in Kotlin

| Page Views: 50

A range is basically an interval with both a start and and an end value.
To create ranges the data types musr be comprabale.
This is done using the range operator(..).

0..9

We then use the in operator to test whether a given value is within the defined parameter limits.
A value is said to be within a given range if it is greater than or equal to the start value and less than or equal to the end value.

0..5   //0,1,2,3,4,5

Integers, Longs and Chars ranges can also be used in a for loop.

EXAMPLE 1

fun main(args: Array<String>) {

    for (i in 0..5) {
        println(i)
    }
}

RESULT

0
1
2
3
4
5

EXAMPLE 2

fun main(args: Array<String>) {
    for (i in 3..18 step 3) {
        println(i)
    }
}

RESULT

3
6
9
12
15
18

EXAMPLE 3

fun main(args: Array<String>) {
    for (c in 'a'..'d') {
        println(c)
    }
}

RESULT

a
b
c
d

EXAMPLE 4

fun main(args: Array<String>) {
    for (c in 'a'..'g' step 2) {
        println(c)
    }
}

RESULT

a
c
e
g

To create ranges you can also employ the downTo and rangeTo. downTo creates a range counting down while rangeTo creates a range counting upto a value.
EXAMPLE 5

fun main(args: Array<String>) {
    for (i in 3 downTo 0) {
        println(i)
    }
}

RESULT

3
2
1
0

EXAMPLE 6

fun main(args: Array<String>) {
    val i = 2
    if (i in 1..10) {
        println(i)
    }
}

RESULT

2

EXAMPLE 7

fun main(args: Array<String>) {
    val num = 8
    if (num !in 1..9) {
        println("No there")
    }else
    {
        println("Its there")
    }
}

RESULT

Its there

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Next Post