Page 97 - CTS - CSA TP - Volume 2
P. 97

COMPUTER SOFTWARE APPLICATION - CITS





                   System.out.print(“Enter the number of rows: “);
                   int rows = scanner.nextInt();
                   System.out.print(“Enter the number of columns: “);

                   int cols = scanner.nextInt();


                   // Create arrays to store the matrices
                   int[][] matrix1 = new int[rows][cols];
                   int[][] matrix2 = new int[rows][cols];
                   int[][] sumMatrix = new int[rows][cols];



                   // Prompt the user to input elements for the first matrix
                   System.out.println(“Enter elements for the first matrix:”);
                   inputMatrix(scanner, matrix1);



                   // Prompt the user to input elements for the second matrix
                   System.out.println(“Enter elements for the second matrix:”);
                   inputMatrix(scanner, matrix2);



                   // Calculate the sum of the matrices
                   for (int i = 0; i < rows; i++) {
                       for (int j = 0; j < cols; j++) {
                           sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
                       }

                   }


                   // Display the sum matrix
                   System.out.println(“Sum of the matrices:”);
                   displayMatrix(sumMatrix);



                   scanner.close(); // Close the scanner
               }



               // Method to input elements into a matrix
               public static void inputMatrix(Scanner scanner, int[][] matrix) {
                   for (int i = 0; i < matrix.length; i++) {
                       for (int j = 0; j < matrix[0].length; j++) {
                           System.out.print(“Enter element [“ + (i+1) + “][“ + (j+1) + “]: “);
                           matrix[i][j] = scanner.nextInt();





                                                           82

                               CITS : IT & ITES - Computer Software Application - Exercise 93
   92   93   94   95   96   97   98   99   100   101   102