MIT-Curricular/OOP/Java/Lab/Week4/PrincipEleSum.java

35 lines
1013 B
Java

import java.util.Scanner;
class PrincipEleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the dimension of the square matrix: ");
int n = sc.nextInt();
int a[][] = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(
"Enter the element at (" + i + "," + j + "): "
);
a[i][j] = sc.nextInt();
}
}
System.out.print("The Principal Elements are: [ ");
// Principal Element Printing and Sum
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
System.out.print(a[i][j] + " ");
sum += a[i][j];
}
}
}
System.out.println("]");
System.out.println("Principal Element Sum: " + sum);
}
}