数组
数组是一个容器,可以容纳固定数量的项目,这些项目应为同一类型。大多数数据结构都利用数组来实现其算法。以下是了解数组概念的重要术语。
- 元素 - 存储在数组中的每个项目称为元素。
- 索引 - 数组中元素的每个位置都有一个数字索引,用于标识元素。
在C语言中,当使用size初始化数组时,它将按以下顺序为其元素分配默认值。
颜色名称 | 效果 |
---|---|
bool | false |
char | 0 |
int | 0 |
float | 0.0 |
double | 0.0f |
void | |
wchar_t | 0 |
遍历数组
此操作将遍历数组的元素。
以下程序遍历并打印数组的元素:
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i < n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
当我们编译并执行上述程序时,它将产生以下结果
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
插入操作
插入操作是将一个或多个数据元素插入数组。根据要求,可以在数组的开头,结尾或任何给定的索引处添加新元素。在这里,我们看到了插入操作的实际实现,我们在数组的末尾添加了数据-
以下是上述算法的实现-
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i < n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
n = n + 1;
while( j >= k) {
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
printf("The array elements after insertion :\n");
for(i = 0; i < n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
当我们编译并执行上述程序时,它将产生以下结果-
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after insertion :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 10
LA[4] = 7
LA[5] = 8
相关资料