Scala program to create a two-dimensional array by using an array of array

Here, we are going to learn how to create a two-dimensional array by using an array of array in Scala programming language?
Submitted by Nidhi, on May 19, 2021 [Last updated : March 10, 2023]

Scala – Creating a 2D Array by using an Array of Array

Here, we will create a two-dimensional array of integers by using an array of array, and then we will print the elements of the array on the console screen.

Scala code to create a two-dimensional array by using an array of array

The source code to create a two-dimensional array by using an array of an array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to create a two-dimensional array 
// by using array of array.

import scala.util.control.Breaks._

object Sample {
  def main(args: Array[String]) {
    var TwoDArr = Array(Array(1, 2, 3, 4, 5), Array(6, 7, 8, 9, 10))
    var i: Int = 0
    var j: Int = 0

    printf("Two dimensional matrix.\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 5) {
        printf("%d ", TwoDArr(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }
  }
}

Output

Two dimensional matrix.
1 2 3 4 5 
6 7 8 9 10

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created a two-dimensional array TwoDArr by using an array of the array that contains 2 rows each row contains 5 items. Then we printed the two-dimensional array by using the nested loop on the console screen.

Scala Array Programs »



Related Programs



All Scala Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.