C语言计算二维数组内圈之和
时间: 2023-11-07 18:01:40 浏览: 60
可以使用两个指针分别指向数组的左上角和右下角,然后向内缩小范围,每次计算一圈的和。
具体实现如下:
```c
#include <stdio.h>
#define ROW 5
#define COL 5
int main() {
int arr[ROW][COL] = {
{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}
};
int left = 0, right = COL - 1, top = 0, bottom = ROW - 1;
int sum = 0;
while (left <= right && top <= bottom) {
// 计算上边
for (int i = left; i <= right; i++) {
sum += arr[top][i];
}
// 计算右边
for (int i = top + 1; i <= bottom; i++) {
sum += arr[i][right];
}
// 如果只有一行或一列,则不需要计算下边和左边
if (top != bottom && left != right) {
// 计算下边
for (int i = right - 1; i >= left; i--) {
sum += arr[bottom][i];
}
// 计算左边
for (int i = bottom - 1; i > top; i--) {
sum += arr[i][left];
}
}
// 缩小范围
left++;
right--;
top++;
bottom--;
}
printf("Sum of inner circle: %d\n", sum);
return 0;
}
```
输出结果为:
```
Sum of inner circle: 135
```
阅读全文