Home »
Scala »
Scala Programs
Scala program to print the right diagonal of MATRIX
Here, we are going to learn how to print the right diagonal of MATRIX in Scala programming language?
Submitted by Nidhi, on May 19, 2021 [Last updated : March 10, 2023]
Scala – Printing the Right Diagonal of Matrix
Here, we will create a 2X2 matrix using a two-dimensional array and then we will read elements of the matrix and then print the right diagonal of the matrix on the console screen.
Scala code to print the right diagonal of matrix
The source code to print the right 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
// right diagonal of MATRIX
object Sample {
def main(args: Array[String]) {
var TwoDArr = Array.ofDim[Int](2, 2)
var i: Int = 0
var j: 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();
}
printf("Right diagonal of matrix:\n")
i = 0;
while (i < 2) {
j = 0;
while (j < 2) {
if ((i + j) == 1)
printf("%d ", TwoDArr(i)(j));
else
printf(" ");
j = j + 1;
}
i = i + 1;
println();
}
}
}
Output
Enter elements of MATRIX:
ELEMENT(0)(0): 20
ELEMENT(0)(1): 31
ELEMENT(1)(0): 42
ELEMENT(1)(1): 53
MATRIX:
20 31
42 53
Right diagonal of matrix:
31
42
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 print the elements of the matrix and also print the right diagonal of the matrix on the console screen.
Scala Array Programs »