Scala program to print the sum of left diagonal elements of MATRIX

Here, we are going to learn how to print the sum of left diagonal elements of MATRIX in Scala programming language?
Submitted by Nidhi, on May 20, 2021 [Last updated : March 10, 2023]

Scala – Sum of Matrix's Left Diagonal Elements

Here, we will create a 3X3 matrix using a two-dimensional array and then we will read elements of the matrix and then print the left diagonal and the sum of its elements of the matrix on the console screen.

Scala code to find the sum of left diagonal elements of matrix

The source code to print the sum of the left diagonal of MATRIX is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to print the 
// sum of left diagonal elements of MATRIX

object Sample {
  def main(args: Array[String]) {
    var TwoDArr = Array.ofDim[Int](3, 3)
    var i: Int = 0
    var j: Int = 0

    var sum: Int = 0

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

    printf("MATRIX:\n")
    i = 0;
    while (i < 3) {
      j = 0;
      while (j < 3) {
        printf("%d ", TwoDArr(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }

    printf("Left diagonal of matrix:\n")
    i = 0;
    while (i < 3) {
      j = 0;
      while (j < 3) {
        if (i == j) {
          sum = sum + TwoDArr(i)(j);
          printf("%d ", TwoDArr(i)(j));
        } else {
          printf(" ");
        }
        j = j + 1;
      }
      i = i + 1;
      println();
    }

    printf("Sum of left diagonal elements is: %d\n", sum);
  }
}

Output

Enter elements of MATRIX:
ELEMENT(0)(0): 10
ELEMENT(0)(1): 20
ELEMENT(0)(2): 30
ELEMENT(1)(0): 40
ELEMENT(1)(1): 50
ELEMENT(1)(2): 60
ELEMENT(2)(0): 70
ELEMENT(2)(1): 80
ELEMENT(2)(2): 90
MATRIX:
10 20 30 
40 50 60 
70 80 90 
Left diagonal of matrix:
10   
 50  
  90 
Sum of left diagonal elements is: 150

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 3X3 matrix using a two-dimensional array, and then we read the elements of the matrix from the user. Then we printed the left diagonal of the matrix and calculated the sum of its elements. After that, we printed the sum of left diagonal elements on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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