### C 语言入门教程

weibo_Slack · 更新于 2020-06-02

# 数组的练习

## 1. 一维数组练习

``````#include <stdio.h>

int main()
{
short sum = 0;
short a[10] = {2, 1, 4, 34, 12, 34, 56, 78, 11, 2};
for (int i = 0; i < 10; i++)
{
sum += a[i]; // 这是一个简写，等价于 sum = sum + a[i];
}

printf("Array Sum: %d\n", sum);
return 0;
}
``````

``````Array Sum: 234
``````

## 2. 多维数组练习

0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16

0 1 5 9 13
1 2 6 10 14
2 3 7 11 15
3 4 8 12 16

``````#include <stdio.h>

int main()
{
short x = 0;
short a[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};

printf("原始数组\n");

for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}

for (int i = 0; i < 4; i++)
{
for (int j = i; j < 4; j++) // 请注意此处是位置交换的关键，我们每次都会缩小交换的范围。
{
x = a[i][j];
a[i][j] = a[j][i];
a[j][i] = x;
}
}

printf("交换位置后的数组\n");

for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}

return 0;
}
``````

``````原始数组
1       2       3       4
5       6       7       8
9       10      11      12
13      14      15      16

1       5       9       13
2       6       10      14
3       7       11      15
4       8       12      16
``````