Scala program to demonstrate the 3D array

Here, we are going to demonstrate the 3D array in Scala programming language.
Submitted by Nidhi, on May 20, 2021 [Last updated : March 10, 2023]

Scala – Multidimensional Arrays (3D Array) Example

Here, we will create a three-dimensional array and then we will read elements for 3D the array from the user. After that, we will print the elements of the 3D array on the console screen.

Scala code to demonstrate the example of multidimensional arrays (3d array)

The source code to demonstrate the 3D array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate 3D array

object Sample {
  def main(args: Array[String]) {
    var ThreeD = Array.ofDim[Int](2, 2, 2)

    var i: Int = 0
    var j: Int = 0
    var k: Int = 0

    var sum: Int = 0

    printf("Enter elements of 3D array:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        k = 0;
        while (k < 2) {
          printf("ELEMENT(%d)(%d)(%d): ", i, j, k);
          ThreeD(i)(j)(k) = scala.io.StdIn.readInt();
          k = k + 1;
        }
        j = j + 1;
      }
      i = i + 1;
    }

    printf("Elements of 3D array:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        k = 0;
        while (k < 2) {
          printf("%d ", ThreeD(i)(j)(k));
          k = k + 1;
        }
        j = j + 1;
      }
      i = i + 1;

    }
    println();
  }
}

Output

Enter elements of 3D array:
ELEMENT(0)(0)(0): 10
ELEMENT(0)(0)(1): 20
ELEMENT(0)(1)(0): 30
ELEMENT(0)(1)(1): 40
ELEMENT(1)(0)(0): 50
ELEMENT(1)(0)(1): 60
ELEMENT(1)(1)(0): 70
ELEMENT(1)(1)(1): 80
Elements of 3D array:
10 20 30 40 50 60 70 80

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 3D array. Then we read the elements for the 3D array from the user and then print them 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.