求解一下,利用指针方法编程,求4×4矩阵两个对角线元素的和。

root@~ #cat duijiao.c #include <stdio.h> int main (void) { int sa=0,sb=0,i,j; int a[4][4]; for(i=0;i<4;i++) { for(j=0;j<4;j++) { scanf("%i",&a[i][j]); } } // for(i=0,j=0;i<4;i++,j++) sa+=a[i][j]; // for(i=0,j=3;i<4;i++,j--) sb+=a[i][j]; printf("Left diagonal sum=%i Right diagonal sum=%i\n",sa,sb); return 0; } root@~ #./duijiao 1 2 3 4 1 2 3 4 1 2 3 4 9 9 9 9 Left diagonal sum=15 Right diagonal sum=18 root@~ #./duijiao 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 Left diagonal sum=18 Right diagonal sum=18 root@~ #
#include <stdio.h> int main (void) { int s = 0, i; int a[4][4] = {0}, * p; for (p = &a[0][0], i = 0; i < 16; p++, i++) { scanf("%d", p); } for (p = &a[0][0], i = 0; i < 4; , p += 5, i++) { s += *p; } printf("The sum of elements on diagonal top-left to bottom-right is: %d", s); for (p = &a[0][3], i = 0; i < 4; , p += 3, i++) { s += *p; } printf("The sum of elements on diagonal top-right to bottom-left is: %d", s); return 0; }