Scala allows us to declare multi-dimensional arrays via the ofDim
function. The function does so by using a matrix format.
We can declare multidimensional arrays using Array.ofDim
.
Array Array.ofDim[data_type](num_rows, num_cols)
The ofDim
function takes two parameters, which are related to the dimensions of the array matrix that will be created. The datatype of the array content also needs to be specified while declaring the array.
num_rows
: the number of rows in the arraynum_cols
: the number of columns in the arrayThe function returns a multidimensional array.
The following code shows how we can use the ofDim
function to make multidimensional arrays in Scala.
object Main extends App{//Using ofDim function to create an array of 3 rows and 4 columnsval mymultiarr= Array.ofDim[Int](3, 4)//Assigning values to all indices in the 2d arraymymultiarr(0)(0) = 1mymultiarr(0)(1) = 2mymultiarr(0)(2) = 3mymultiarr(0)(3) = 4mymultiarr(1)(0) = 5mymultiarr(1)(1) = 6mymultiarr(1)(2) = 7mymultiarr(1)(3) = 8mymultiarr(2)(0) = 9mymultiarr(2)(1) = 10mymultiarr(2)(2) = 11mymultiarr(2)(3) = 12for(i<-0 to 2) //indexing the array{for(j<-0 to 3){print(mymultiarr(i)(j))print(" ")}println()}}
Free Resources