c语言 对角线数据 输入一个5×5的数组,分别求其主对角线和辅对角线上元素之和

2024-11-19 23:12:05
推荐回答(2个)
回答1:

#include
void main()
{
int a[5][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25},i,j,sum1=0,sum2=0;
for (i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(i==j)
sum1=sum1+a[i][j];
if(i+j==4)
sum2=sum2+a[i][j];
}

}

printf("%d\n%d\n",sum1,sum2);

}

回答2:

#include
void main()
{
int a[5][5]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25},i,j,sum1=0,sum2=0;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
for (i=0;i<5;i++)
{
sum1+=a[i][i];
sum2+=a[i][4-i];
}

printf("sum1=%d\nsum2=%d\n",sum1,sum2);

}