C++求正方形矩阵边缘元素与边缘元素和

C++求正方形矩阵边缘元素与边缘元素和

输入

4

1 2 3 4

1 2 3 4

1 2 3 4

1 2 3 4

输出

1 2 3 4

1 4

1 4

1 2 3 4

30

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int main(){
	long long int sum=0;
    int n;
	cin>>n;
	int arr[n+5][n+5];
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			cin>>arr[i][j];
		}
	} 
	cout<<endl;
	for(int i=0;i<n;i++){
		if(i==0||i==n-1){
			for(int j=0;j<n;j++){
				cout<<arr[i][j]<<" ";
				sum+=arr[i][j];
			}
			cout<<endl;
		}else{
			sum+=arr[i][0];
			sum+=arr[i][n-1];
			cout<<arr[i][0]<<" ";
			for(int j=1;j<n-1;j++){
				cout<<"  ";
			}
			cout<<arr[i][n-1];
			cout<<endl;
		}
	}
	cout<<sum;
	return 0;
}