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);
			 
		}
	}
}

猜你喜欢

转载自blog.csdn.net/m0_64206989/article/details/127498522