Diagonal Sums
Completed
Read an n×n matrix and print the sum of the main diagonal and of the anti-diagonal.
Input
n, then n rows.
Output
Two lines.
Example
Input
3 1 2 3 4 5 6 7 8 9
Output
15 15
Editor
Java
Hints
Main diagonal: i == j. Anti-diagonal: i + j == n - 1.
Solution explanation
You don't even need to store the matrix if you only need sums.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int main = 0, anti = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int v = sc.nextInt();
if (i == j) {
main += v;
}
if (i + j == n - 1) {
anti += v;
}
}
}
System.out.println(main);
System.out.println(anti);
}
}