1103: 求矩阵的两对角线上的元素之和

输入

矩阵的行数N
和一个N*N的整数矩阵a[N][N](N<=10)

输出

所输矩阵的两对角线上的元素之和

样例输入

3
1 2 3 
4 5 6 
7 8 9

样例输出

25

import java.util.Scanner;

public class Main1103 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNextInt()) {
			int sum=0;
			int n = sc.nextInt();
			int arr[][] = new int[n][n];
			
			for(int i=0;i<n;i++) {
				for(int j=0;j<n;j++) {
					int m=sc.nextInt();
					arr[i][j]=m;
					
				}
			}
			
			for(int i=0;i<n;i++) {
			    for(int j=0;j<n;j++) {
				    if(i==j||i+j==n-1) {
				        sum=sum+arr[i][j];
				    }
			    }
			}
			System.out.println(sum);
			 
		}
	}
}

版权声明:本文为m0_64206989原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。