Kotlin. Ranges (Intervals)

Ranges (Intervals). The .. operator. Applying intervals in conditions (if), loops (for), selection (when). The in operator. Interval types IntRange, CharRange, LongRange


Contents


Search other resources:

1. Ranges (intervals). Declaration syntax. Operator . .

Intervals or ranges allow you to specify a sequence of possible values between some starting and ending value. The intervals are defined using the operator .. and in the general case have the following form

begin_value .. end_value

here

  • begin_value – a value that defines the beginning of the range;
  • end_value – final range value.

 

2. Creating variables that are ranges. Assigning a range to a reference

To create a read-only variable that is a range, use the following syntax

val varName = begin_value .. end_value

To create a range mutable variable, you need to use the following notation

var varName = begin_value .. end_value

If a variable is declared as a range, then its value can be overridden by another range of the same range type.

 

3. Range types CharRange, IntRange, LongRange. Declaring and using an interval type variable

The Kotlin language supports three interval types CharRange, IntRange, LongRange, which define the range of values for char, int, long, respectively. It is allowed to declare a variable of a range type and then assign appropriate ranges to it.

Example.

// Declare variables of interval types

// 1. Range of values of type int
var seconds : IntRange
seconds = 0..59

val miliseconds : IntRange = 0..100

// 2. Range of values of type long
var bigNumbers : LongRange = 0..1_000_000_000_000_000

// reassigning a range of type long
bigNumbers = 0..1_000L

// 3. Range of char values
var chars : CharRange // character type
chars = 'a'..'z'

// reassigning a range of type char
chars = 'A'..'Z'

// this is not possible - compilation error, mismatch of CharRange and IntRange types
//chars = 1..10

 

4. The in operator. Combining the in operator with intervals

The in operator is used to determine if a value is included in an interval. To check if a value is within the specified range, use the following syntax

valueName in begin_value .. end_value

here

  • valueName – a variable or value that is checked for belonging to an interval ranging from begin_value to end_value.

The result of the in operator is true (if the variable is within the range) or false (the variable is outside the range).

 

5. Using ranges in the if statement. Examples
5.1. Determining the belonging of the day of the week

Task. The number of the day of the week is set (1..7). Determine what day it is: working or weekend.

Solution.

 

fun main(args:Array<String>) {
  // Ranges, the .. operator

  // 1. Declare variables
  val day : Int

  // 2. Input the day of the week
  print("day = ")
  day = readLine().toString().toInt()

  // 3. Calculation
  if (day in 1..5)
    println("Workday.")
  else
  if (day in 6..7)
    println("Day off.")
  else
    println("Incorrect input.")
}

Test example

day = 3
Workday.

 

5.2. Determination of the age category of a person

Task. Develop a program that asks for a user’s name and age and determines which age category he belongs to:

  • from 1 to 10 years old – a child;
  • from 11 to 15 years old – teenager;
  • from 16 to 20 years old – a younker;
  • from 21 to 30 years old – a young person;
  • after 31 years – an adult.

Solution.

fun main(args:Array<String>) {
  // Ranges, operator ..

  // 1. Declare variables
  val name : String
  val age : Int

  // 2. Input data
  print("name = ")
  name = readLine().toString()
  print("age = ")
  age = readLine().toString().toInt()

  // 3. Checking if the input is correct
  if (age<=0)
    println("Incorrect input")

  // 4. Calculations
  if (age in 1..10)
    println("Child.") 
  else
  if (age in 11..15)
    println("Teenager") 
  else
  if (age in 16..20)
    println("Younker (young woman)") 
  else
  if (age in 21..30)
    println("Young person") 
  else
    println("Adult")
}

Test example

name = Ihor
age = 49
Adult

 

6. Using ranges in the when operator
6.1. Determining the season by the number of the month

Task. Using the when operator and ranges, develop a program that, by the number of the month (1..12), determines the name of the season to which it belongs.

Solution.

fun main(args:Array<String>) {
  // Ranges, operators in, ..

  // 1. Declare variables
  val month : Int

  // 2. Input data
  print("month = ")
  month = readLine().toString().toInt()

  // 3. Calculation
  when (month) {
    in 1..2, 12 -> println("Winter")
    in 3..5 -> println("Spring")
    in 6..8 -> println("Summer")
    in 9..11 -> println("Autumn")
    else -> println("Incorrect input.")
  }
}

Test example

month = 8
Summer

 

6.2. Determination of the zodiac sign

Task. A day number and a month number are specified, which determine the person’s date of birth. Develop a program that determines which sign of the zodiac belongs to a person’s date of birth:

  • 20.01 – 18.02 – Aquarius
  • 19.02 – 20.03 – Fish
  • 21.03 – 19.04 – Aries
  • 20.04 – 20.05 – Taurus
  • 21.05 – 21.06 – Gemini
  • 22.06 – 22.07 – Cancer
  • 23.07 – 22.08 – Leo
  • 23.08 – 22.09 – Virgo
  • 23.09 – 22.10 – Libra
  • 23.10 – 22.11 – Scorpio
  • 23.11 – 21.12 – Sagittarius
  • 22.12 – 19.01 – Capricorn

In the program, consider that the year is not a leap year.

Solution.

fun main(args:Array<String>) {
  // Ranges, operators in, ..

  // 1. Declare variables
  val day : Int
  val month : Int

  // 2. Input data
  print("day = ")
  day = readLine().toString().toInt()
  print("month = ")
  month = readLine().toString().toInt()

  // 3. Calculation
  when {
    (month==1)&&(day in 1..19) ||
      (month==12)&&(day in 22..31) -> println("Capricorn")
    (month==1)&&(day in 20..31) ||
      (month==2)&&(day in 1..18) -> println("Aquarius")
    (month==2)&&(day in 19..28) ||
      (month==3)&&(day in 1..20) -> println("Fish")
    (month==3)&&(day in 21..31) ||
      (month==4)&&(day in 1..19) -> println("Aries")
    (month==4)&&(day in 20..30) ||
      (month==5)&&(day in 1..20) -> println("Taurus")
    (month==5)&&(day in 21..31) ||
      (month==6)&&(day in 1..21) -> println("Gemini")
    (month==6)&&(day in 22..30) ||
      (month==7)&&(day in 1..22) -> println("Cancer")
    (month==7)&&(day in 23..31) ||
      (month==8)&&(day in 1..22) -> println("Leo")
    (month==8)&&(day in 23..31) ||
      (month==9)&&(day in 1..22) -> println("Virgo")
    (month==9)&&(day in 23..30) ||
      (month==10)&&(day in 1..22) -> println("Libra")
    (month==10)&&(day in 23..31) ||
      (month==11)&&(day in 1..22) -> println("Scorpio")
    (month==11)&&(day in 23..30) ||
      (month==12)&&(day in 1..21) -> println("Sagittarius")
    else -> println("Incorrect input.")
  }
}

Test example

day = 14
month = 1
Capricorn

 

7. Using ranges in a for loop statement
7.1. Convert pounds to kilograms

Task. Print a pound to kilogram conversion table for pounds from 1 to 10 (1 pound = 453 grams).

Solution.

fun main(args:Array<String>) {
  // Ranges, operators in, ..

  // Print correspondence table 1 lb = 0.453 kg

  // 1. Declare variables
  var lb : Int
  var kg : Double

  // 2. Input table
  for (lb in 1..10) {
    kg = lb * 0.453
    println("lb.: " + lb + " => " + kg + " kg.")
  }
}

The result of the program

lb.: 1 => 0.453 kg.
lb.: 2 => 0.906 kg.
lb.: 3 => 1.359 kg.
lb.: 4 => 1.812 kg.
lb.: 5 => 2.265 kg.
lb.: 6 => 2.718 kg.
lb.: 7 => 3.1710000000000003 kg.
lb.: 8 => 3.624 kg.
lb.: 9 => 4.077 kg.
lb.: 10 => 4.53 kg.

 

7.2. The calculation of the arithmetic mean of the numbers

Task. A natural number n and real numbers a1, a2, …, an are given. Determine the arithmetic mean of these numbers. Do not use arrays in the program.

Solution.

fun main(args:Array<String>) {
  // Ranges, operators in, ..
  // Determine the arithmetic mean of a sequence of numbers
  // 1. Declare variables
  var avg : Double = 0.0
  val n : Int
  var a : Double

  // 2. Input n
  print("n = ")
  n = readLine().toString().toInt()

  // 3. Calculation cycle, interval 1..n is used
  for (i : Int in 1..n) {
    // input number
    print("=> ")
    a = readLine().toString().toDouble()

    // add to the summ
    avg += a
  }

  // 4. Display average
  avg /= n
  println("average = " + avg)
}

Test example

n = 5
=> 1.2
=> 1.4
=> 1.6
=> 1.7
=> 1.1
average = 1.4

 


Related topics