Page 98 - CTS - CSA TP - Volume 2
P. 98
COMPUTER SOFTWARE APPLICATION - CITS
}
}
}
// Method to display a matrix
public static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + “ “);
}
System.out.println();
}
}
}
Explanation:
• This program allows the user to input two matrices of the same dimensions (number of rows and
columns) through the keyboard and then displays their sum.
• It first prompts the user to enter the dimensions (number of rows and columns) of the matrices.
• Two 2D arrays, matrix1 and matrix2, are created to store the input matrices, and another array,
sumMatrix, is created to store the sum of the matrices.
• The inputMatrix() method is used to prompt the user to input elements for each matrix.
• The displayMatrix() method is used to display the elements of a matrix.
• After inputting the elements for both matrices, the program calculates the sum of the corresponding
elements from the two matrices and stores the result in the sumMatrix array.
• Finally, it displays the sum matrix to the user.
This program demonstrates the use of 2D arrays in Java to represent matrices and perform basic matrix
operations, such as addition. It illustrates the inputting of matrix elements through the keyboard, calculating the
sum of two matrices, and displaying the resulting sum matrix.
Related Tasks:
Develop the following java programs:
1 Display the upper diagonal elements and its sum of a matrix
2 Display the upper triangular elements of a matrix
3 Display the transpose of a matrix
4 Display the product of two matrices
5 Check the given matrix is Symmetric or not (A symmetric matrix is a square matrix where A [i][j]=A[j][i]. ie.,
A= AT)
83
CITS : IT & ITES - Computer Software Application - Exercise 93