JAVA SP T


Lets dive into snapshot of my programs!💻

9. Program to find the sum of each row and each column of a matrix

💡Code:

  import java.util.Scanner;

              public class MatrixSum7078 {
                  public static void main(String[] args) {
                      Scanner scanner = new Scanner(System.in);
              
                      // Get the dimensions of the matrix from the user
                      System.out.print("Enter the number of rows: ");
                      int rows = scanner.nextInt();
                      System.out.print("Enter the number of columns: ");
                      int columns = scanner.nextInt();
              
                      // Create the matrix
                      int[][] matrix = new int[rows][columns];
                      System.out.println("Enter elements for the matrix:");
                      inputMatrix(matrix, scanner);
              
                      // Find the sum of each row and each column
                      int[] rowSum = new int[rows];
                      int[] columnSum = new int[columns];
              
                      for (int i = 0; i < rows; i++) {
                          for (int j = 0; j < columns; j++) {
                              rowSum[i] += matrix[i][j];
                              columnSum[j] += matrix[i][j];
                          }
                      }
              
                      // Display the result
                      System.out.println("Sum of Each Row:");
                      displayArray(rowSum);
              
                      System.out.println("Sum of Each Column:");
                      displayArray(columnSum);
              
                      // Close the scanner
                      scanner.close();
                  }
              
                  // Function to input elements into a matrix
                  private static void inputMatrix(int[][] matrix, Scanner scanner) {
                      for (int i = 0; i < matrix.length; i++) {
                          for (int j = 0; j < matrix[0].length; j++) {
                              System.out.print("Enter element at position [" + (i + 1) + "][" + (j + 1) + "]: ");
                              matrix[i][j] = scanner.nextInt();
                          }
                      }
                  }
              
                  // Function to display the elements of an array
                  private static void displayArray(int[] array) {
                      for (int element : array) {
                          System.out.print(element + " ");
                      }
                      System.out.println();
                  }
              }
              

📸Output :

output