Q:

Scala program to calculate the sum of rows of matrix elements

belongs to collection: Scala Array Programs

0

Here, we will create a 2X2 matrix using a two-dimensional array and then we will read elements of the matrix and calculate the sum of rows of matrix elements.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to calculate the sum of rows of matrix elements is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to calculate the 
// sum of rows of matrix elements

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

    var sum: Int = 0

    printf("Enter elements of MATRIX:\n")
    i = 0;
    while (i < 2) {
      j = 0;
      while (j < 2) {
        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 < 2) {
      j = 0;
      while (j < 2) {
        printf("%d ", TwoDArr(i)(j));
        j = j + 1;
      }
      i = i + 1;
      println();
    }

    i = 0;
    while (i < 2) {
      j = 0;
      sum = 0;
      while (j < 2) {
        sum = sum + TwoDArr(i)(j);
        j = j + 1;
      }
      printf("Sum of row(%d): %d\n", i, sum);
      i = i + 1;
    }
  }
}

Output:

Enter elements of MATRIX:
ELEMENT(0)(0): 10
ELEMENT(0)(1): 20
ELEMENT(1)(0): 30
ELEMENT(1)(1): 40
MATRIX:
10 20 
30 40
Sum of row(0): 30
Sum of row(1): 70

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 2X2 matrix using a two-dimensional array, and then we read the elements of the matrix from the user. Then we calculated the sum of rows of matrix elements. After that, we printed the elements of the matrix and the sum of rows element on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to calculate the sum of columns of m... >>
<< Scala program to calculate the sum of matrix eleme...