Home »
Scala »
Scala Programs
Scala program to add two matrices
Here, we are going to learn how to add two matrices in Scala programming language?
Submitted by Nidhi, on May 20, 2021 [Last updated : March 10, 2023]
Scala – Add Two Matrices
Here, we will create three 2X2 matrices using a two-dimensional array and then we will read elements for two matrices. After that, we will add two matrices and assign the result to the third matrix.
Scala code to add elements of two matrices
The source code to add two matrices is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to add two matrices
object Sample {
def main(args: Array[String]) {
var Matrix1 = Array.ofDim[Int](2, 2)
var Matrix2 = Array.ofDim[Int](2, 2)
var Matrix3 = Array.ofDim[Int](2, 2)
var i: Int = 0
var j: Int = 0
printf("Enter elements of MATRIX1:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
printf("ELEMENT(%d)(%d): ", i, j);
Matrix1(i)(j) = scala.io.StdIn.readInt();
j = j + 1;
}
i = i + 1;
}
printf("Enter elements of MATRIX2:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
printf("ELEMENT(%d)(%d): ", i, j);
Matrix2(i)(j) = scala.io.StdIn.readInt();
j = j + 1;
}
i = i + 1;
}
//Add Matrix1 and Matrix2
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
Matrix3(i)(j) = Matrix1(i)(j) + Matrix2(i)(j)
j = j + 1;
}
i = i + 1;
}
printf("MATRIX1:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
printf("%d ", Matrix1(i)(j));
j = j + 1;
}
i = i + 1;
println();
}
printf("MATRIX2:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
printf("%d ", Matrix2(i)(j));
j = j + 1;
}
i = i + 1;
println();
}
printf("Addition of Matrix1 and Matrix2:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
printf("%d ", Matrix3(i)(j));
j = j + 1;
}
i = i + 1;
println();
}
}
}
Output
Enter elements of MATRIX1:
ELEMENT(0)(0): 10
ELEMENT(0)(1): 20
ELEMENT(1)(0): 30
ELEMENT(1)(1): 40
Enter elements of MATRIX2:
ELEMENT(0)(0): 20
ELEMENT(0)(1): 30
ELEMENT(1)(0): 40
ELEMENT(1)(1): 50
MATRIX1:
10 20
30 40
MATRIX2:
20 30
40 50
Addition of Matrix1 and Matrix2:
30 50
70 90
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 »