Sum of the Diagonals of a Square Matrix
Problem
Read a square matrix (r = c = n). Print the sum of the main diagonal (top-left to bottom-right) and the sum of the anti-diagonal (top-right to bottom-left) in the form main=<sum> anti=<sum>. If n is odd, the middle element is counted in both sums.
Constraints
- 1 <= n <= 100
Examples
Input
3 3 1 2 3 4 5 6 7 8 9
Output
main=15 anti=15
Solutions
No nested loop is needed. In row i the main diagonal is column i, and the anti-diagonal is column n - 1 - i.
/*
* Problem : Process a matrix.
* Input : r and c, then r rows of c integers.
* Output : Two sums.
* Approach: One loop is enough.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(int[][] m) {
int n = m.length;
long main = 0;
long anti = 0;
for (int i = 0; i < n; i++) {
// Step 1: The main diagonal has the positions (0,0), (1,1), (2,2), ...
main += m[i][i];
// Step 2: The anti-diagonal has the positions (0,n-1), (1,n-2), ...
anti += m[i][n - 1 - i];
}
// Step 3: Print both sums.
return "main=" + main + " anti=" + anti;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(solve(m));
}
}
Hints (1)
- Which column is the anti-diagonal in row 0?