數組
數組是一個容器,可以容納固定數量的項目,這些項目應爲同一類型。大多數數據結構都利用數組來實現其算法。以下是瞭解數組概念的重要術語。
- 元素 - 存儲在數組中的每個項目稱爲元素。
- 索引 - 數組中元素的每個位置都有一個數字索引,用於標識元素。
在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
相關資料