Created
February 14, 2022 08:35
-
-
Save aadipoddar/7f82adf089ea48d3e1951d447040c0a4 to your computer and use it in GitHub Desktop.
Sum of Diagonals and Symmetric Matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a Program to input a square Matrix of size between 2 to 10. | |
Find if the Matrix is symmetric or not. | |
Find the Sum to the Diagonals of the Matrix | |
EG: | |
INPUT: | |
Size : 3 | |
OUTPUT: | |
ORIGINAL MATRIX | |
1 1 1 | |
1 1 1 | |
1 1 1 | |
The sum of the diagonal elements = 6 | |
*/ | |
import java.util.*; | |
class DiagonalSum | |
{ | |
public static void main() | |
{ | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the size of array"); | |
int m = sc.nextInt(); | |
if(m <= 2 || m >= 10) //Checking if Array is out of range or not | |
{ | |
System.out.println("THE MATRIX IS OUT OF RANGE"); | |
return; | |
} | |
int arr[][] = new int[m][m]; | |
System.out.println("Enter the elements of the array"); | |
for(int i = 0; i < m; i++) | |
for(int j = 0; j < m; j++) | |
arr[i][j] = sc.nextInt(); | |
System.out.println("ORIGINAL MATRIX"); | |
for(int i = 0; i < m; i++) | |
{ | |
for(int j = 0; j < m; j++) | |
System.out.print(arr[i][j] + "\t"); //Space for better formatting | |
System.out.println(); | |
} | |
boolean isSymmetric = true; | |
//Checking if array is Symmetric | |
for(int i = 0; i < m; i++) | |
for(int j = 0; j < m; j++) | |
if(arr[i][j] != arr[j][i]) | |
isSymmetric = false; | |
if(!isSymmetric) | |
System.out.println("THE GIVEN MATRIX IS NOT SYMMETRIC"); | |
int sum = 0; | |
//Calculate the sum of first diagonal | |
for(int i = 0; i < m; i++) | |
for(int j = 0; j < m; j++) | |
if(i == j) //Checking if element is a diagonal element | |
sum += arr[i][j]; | |
//Calculate the sum of second diagonal | |
for(int i = 0, j = m - 1; i < m && j >= 0; i++, j--) | |
sum += arr[i][j]; | |
System.out.println("The sum of the diagonal elements = " + sum); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment