Question: ## Write a program in Java to take two square Matrices. Your task is to find the third highest from the first matrix and find the third lowest from the second matrix and print the sum of both of them.
Test Data:
Input the rows and columns of first matrix: 2 2
Input the rows and columns of second matrix: 2 2
Input elements in the first matrix:
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8
Expected Output :
The third highest of the first matrix is: 2
The third lowest of the second matrix is: 7
The sum of both is : 9.
Solution:
package question02;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a, b;
System.out.print("\nEnter The Number of ROWs & COLOUMs For The First Matrix : ");
int row1 = input.nextInt();
int col1 = input.nextInt();
System.out.print("\nEnter The Number of ROWs & COLOUMs For The Second Matrix : ");
int row2 = input.nextInt();
int col2 = input.nextInt();
int[][] mat1 = new int[row1][col1];
int[][] mat2 = new int[row2][col2];
ArrayList<Integer> M1 = new ArrayList<>();
ArrayList<Integer> M2 = new ArrayList<>();
System.out.println("\n\n\n\nEnter Elements For The First MATRIX ....\n");
for (a = 0; a < row1; a++) {
for (b = 0; b < col1; b++) {
System.out.printf("\n\nelement - [%d],[%d] = ", a, b);
mat1[a][b] = input.nextInt();
M1.add(mat1[a][b]);
}
}
System.out.println("\n\n\n\nEnter Elements For The Second MATRIX ....\n");
for (a = 0; a < row2; a++) {
for (b = 0; b < col2; b++) {
System.out.printf("\n\nelement - [%d],[%d] = ", a, b);
mat2[a][b] = input.nextInt();
M2.add(mat2[a][b]);
}
}
System.out.println("\n\n");
System.out.print("\n\n The First Matrix is :");
for (a = 0; a < row1; a++) {
for (b = 0; b < col1; b++) {
System.out.print("\t " + mat1[a][b]);
}
System.out.print(" \n");
System.out.print("\t\t");
}
System.out.println("\n\n");
System.out.print("\n The Second Matrix is :");
for (a = 0; a < row2; a++) {
for (b = 0; b < col2; b++) {
System.out.print("\t " + mat2[a][b]);
}
System.out.print(" \n\t");
System.out.print("\t\t");
}
System.out.println("\n\n");
Collections.sort(M1, Collections.reverseOrder());
Collections.sort(M2);
int th = M1.get(2);
System.out.println("The Third Highest of The First Matrix is : " + th);
int tl = M2.get(2);
System.out.println("The Third Lowest of The Second Matrix is : " + tl);
System.out.println();
System.out.println("The Sum of both is : " + (th + tl));
}
}