Categories

# 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{
System.out.print("Matrix size: ");
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++){
}
}
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 replies on “Add Non-Diagonal Elements of a Matrix”

sayan ranasays:

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

sayan ranasays:

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(int i = 0; i < m; i++){