013. 遍历数组并处理每个元素
在C语言中,遍历数组并处理每个元素是常见的操作。通常使用循环语句(如for
循环或while
循环)来实现数组的遍历。以下将通过具体示例展示如何遍历数组并处理每个元素。
示例1:使用for
循环遍历一维数组
假设我们有一个一维数组,需要遍历并打印每个元素。
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // 声明并初始化数组
int size = sizeof(arr) / sizeof(arr[0]); // 计算数组的大小
// 使用for循环遍历数组
for (int i = 0; i < size; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}
return 0;
}
输出结果
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
示例2:使用for
循环计算数组元素的总和
假设我们需要计算数组中所有元素的总和。
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // 声明并初始化数组
int size = sizeof(arr) / sizeof(arr[0]); // 计算数组的大小
int sum = 0; // 用于存储总和
// 使用for循环遍历数组并计算总和
for (int i = 0; i < size; i++) {
sum += arr[i];
}
printf("The sum of the array elements is: %d\n", sum);
return 0;
}
输出结果
The sum of the array elements is: 15
示例3:使用for
循环查找数组中的最大值
假设我们需要找到数组中的最大值。
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // 声明并初始化数组
int size = sizeof(arr) / sizeof(arr[0]); // 计算数组的大小
int max = arr[0]; // 假设第一个元素是最大值
// 使用for循环遍历数组并查找最大值
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
printf("The maximum value in the array is: %d\n", max);
return 0;
}
输出结果
The maximum value in the array is: 5
示例4:使用while
循环遍历数组
我们也可以使用while
循环来遍历数组。
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5}; // 声明并初始化数组
int size = sizeof(arr) / sizeof(arr[0]); // 计算数组的大小
int i = 0; // 初始化索引
// 使用while循环遍历数组
while (i < size) {
printf("Element at index %d: %d\n", i, arr[i]);
i++;
}
return 0;
}
输出结果
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5
示例5:遍历二维数组
假设我们有一个二维数组,需要遍历并打印每个元素。
#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}; // 声明并初始化二维数组
int rows = sizeof(matrix) / sizeof(matrix[0]); // 计算行数
int cols = sizeof(matrix[0]) / sizeof(matrix[0][0]); // 计算列数
// 使用嵌套for循环遍历二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element at [%d][%d]: %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
输出结果
Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [0][3]: 4
Element at [1][0]: 5
Element at [1][1]: 6
Element at [1][2]: 7
Element at [1][3]: 8
Element at [2][0]: 9
Element at [2][1]: 10
Element at [2][2]: 11
Element at [2][3]: 12
视频讲解
BiliBili: 视睿网络-哔哩哔哩视频 (bilibili.com)