Add Non-Diagonal Elements of a Matrix

Write a program to allow the user to create an integer matrix of order M × M, where M > 2 and M < 9.

Display a suitable message for an invalid matrix size.

Also allow the user to enter numbers into this matrix.

Now find the sum of only those elements that do not appear on the two diagonals of the given matrix.

Also find the highest number in this matrix.

import java.io.*;
class Matrix{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Matrix size: ");
        int m = Integer.parseInt(br.readLine());
        if(m < 3 || m > 9){
            System.out.println("Size out of range!");
            return;
        }
        int a[][] = new int[m][m];
        int sum = 0;
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                a[i][j] = Integer.parseInt(br.readLine());
            }
        }
        int highest = a[0][0];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                if(highest < a[i][j])
                    highest = a[i][j];
                if(i == j || i + j == m - 1)
                    continue;
                sum += a[i][j];
            }
        }
        System.out.println("Sum of non-diagonal elements: " + sum);
        System.out.println("Highest element: " + highest);
    }
}

3 thoughts on “Add Non-Diagonal Elements of a Matrix

  1. Sir,a program is given which states that :
    WAP in Java to accept a string & print all the consecutive and repeated characters present in the string.
    Sample Input: understanding computer science
    Sample Output:
    Consecutive characters:
    d e r s s t
    Repeated characters:
    u n e r s t i c

  2. Write a program to allow the user to create an integer matrix of order M × M, where M > 2 and M < 9.

    Display a suitable message for an invalid matrix size.

    Also allow the user to enter numbers into this matrix.Display the highest number among the non-diagonal elements.

    • For highest number among non-diagonal elements, make changes in the loop as follows:

      for(int i = 0; i < m; i++){
          for(int j = 0; j < m; j++){
              if(i == j || i + j == m - 1)
                  continue;
              else if(highest < a[i][j])
                  highest = a[i][j];
          }
      }

Leave a Reply