Java经典编程题50道之二十九
求一个3*3矩阵对角线元素之和。
public class Example29 {
public static void main(String[] args) {
int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
sum(a);
}
public static void sum(int[][] a) {
System.out.println("您输入的3*3矩阵是:");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + "\t");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (i == j) {
sum += a[i][j];
}
}
}
System.out.println("对角线之和是:" + sum);
}
}