Scala multi dimensionalArray

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 15:57:39 Viewed : 209


Scala multi dimensionalArray 

ยท        Syntax for Multidimensional Array

var arrayName = Array.ofDim[ArrayType](NoOfRows,NoOfColumns) or  

var arrayName = Array(Array(element...), Array(element...), ...)   

Example 3:

     Following example illustrates about Scala multi dimensional Array

     Save the file as โˆ’  MultiArrayDec.scala 

MultiArrayDec.scala 

package runnerdev

object MulitDimeArrayEx1 { 

  def main(args: Array[String]) {

    var arrayObj = new MultiArrayDec()

    arrayObj.show()

  }

}

class MultiArrayDec {

  var multiArray = Array(Array(1, "cat", "One", 4, 5), Array(6, 7, "dog", 9, 10)) // Creating multidimensional array

  def show() {

    for (x <- 0 to 1) { // Traversing elements using loop

      for (y <- 0 to 4) {

        print(" " + multiArray(x)(y))

      }

      println()

    }

  }

}

compile and run the above example as follows 

scala> scalac MultiArrayDec.scala

scala> scala MultiArrayDec

Output :

1 cat One 4 5

 6 7 dog 9 10  

Example 3:

      Following example illustrates about Scala multi dimensional Array(ofDim)

      Save the file as โˆ’  MulitDimeArrayEx2.scala 

MulitDimeArrayEx2.scala

package runnerdev 

object MulitDimeArrayEx2 { 

  def main(args: Array[String]) {

    var arrayObj = new MultiArrayDec1()

    arrayObj.show()

  }

}

class MultiArrayDec1 {

  var arr = Array.ofDim[Int](2, 2) // Creating multidimensional array

  arr(1)(0) = 10 // Assigning value

  arr(1)(0) = 11 // Assigning value

  arr(1)(1) = 99 // Assigning value

  def show() {

    for (x <- 0 to 1) { // Traversing elements by using loop

      for (y <- 0 to 1) {

        print(" " + arr(x)(y))

      }

      println()

    }

    println("Third Element = " + arr(1)(1)) // Accessing elements by using index

  }

}

compile and run the above example as follows 

scala> scalac MultiArrayDec1.scala

scala> scala MultiArrayDec1

Output :

 Output:

 0 0

 11 99

Third Element = 99

 

Search
Sub-Categories
Related Articles

Leave a Comment: