目录
- [一.数组遍历原理]
- [二.数组遍历实战]
- [1.遍历数组查询数组中的元素]
- [2.遍历数组修改数组中的元素]
- [三.猜你喜欢]
零基础 C/C++ 学习路线推荐 : [C/C++ 学习目录]>> [C 语言基础入门]
一.数组遍历原理
在 [C]数组定义和初始化中详细的介绍了关于数组五种初始化方法,这些初始化方式其实在开发中还是蛮实用的;
对于数组元素的访问和修改是通过数组下标的方式来解决的,[数组遍历]的原理也是一样,通过 [while
循环]或者 [for
循环]直接遍历数组下标从而达到访问或者修改数组值的目的;
需要注意的是:
- A.数组中每个元素的数据类型必须相同,例如:
int a[4]
,每个元素都必须为int
; - B.[数组]长度
length
最好是整数或者常量表达式; - C.访问数组元素时,下标的取值范围为
0≤ index < length
; - D.数组是一个整体,它的内存是连续的;
二.数组遍历实战
1.遍历数组查询数组中的元素
/******************************************************************************************/
#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
void main()
{
int a[5] = {1,2,3,4,5};
int len = sizeof(a)/sizeof(int); //计算数组元素个数
int index = 0;
while (index < len)
{
printf("index:%d value:%d\n", index,a[index]);//当前的元素
index++;//数组元素索引值+1
}
system("pause");
}
/*
输出:
index:0 value:1
index:1 value:2
index:2 value:3
index:3 value:4
index:4 value:5
请按任意键继续. . .
*/
2.遍历数组修改数组中的元素
/******************************************************************************************/
#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
void main()
{
int a[5] = {1,2,3,4,5};
int len = sizeof(a)/sizeof(int); //计算数组元素个数
for (int index = 0;index<len;index++)
{
a[index] *= 10;//等价: a[index] = a[index] * 10;
printf("index:%d value:%d\n", index,a[index]);//当前的元素
}
system("pause");
}
/*
输出:
index:0 value:10
index:1 value:20
index:2 value:30
index:3 value:40
index:4 value:50
请按任意键继续. . .
*/