30% Therapy – 40% Practice – 30% Work project

Scala Collections – Array with Range



Use of range() method to generate an array containing a sequence of increasing integers in a given range. You can use final argument as step to create the sequence; if you do not use final argument, then step would be assumed as 1.

Let us take an example of creating an array of range (10, 20, 2): It means creating an array with elements between 10 and 20 and range difference 2. Elements in the array are 10, 12, 14, 16, and 18.

Another example: range (10, 20). Here range difference is not given so by default it assumes 1 element. It create an array with the elements in between 10 and 20 with range difference 1. Elements in the array are 10, 11, 12, 13, …, and 19.

The following example program shows how to create an array with ranges.

Example

import Array._
object Demo {
   def main(args: Array[String]) {
      var myList1 = range(10, 20, 2)
      var myList2 = range(10,20)
      // Print all the array elements
      for ( x <- myList1 ) {
         print( " " &plus; x )
      }
      println()
      for ( x <- myList2 ) {
         print( " " &plus; x )
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

>scalac Demo.scala
>scala Demo

Output

10 12 14 16 18
10 11 12 13 14 15 16 17 18 19
Translate »