陣列是一組固定數量的相同資料類型的項目。這些元素儲存在記憶體中的連續記憶體位置。
可以使用方括號「[]」和陣列名稱像a[4]、a[3]等從其索引值存取值的每個單一元素。
在c/c 程式語言中,透過定義陣列的類型和長度(元素數量)來宣告陣列。下面的語法顯示了在c/c 中宣告數組的方法−
data_tpye array_name[length];
例如,聲明一個 float 類型的數組,名稱為長度為 10 的百分比。
float percentage[10]
在C 程式語言中,您有多種方式可以初始化值,即逐個初始化或使用單一語句聲明所有值。
逐一初始化-
percentage[5] = 45.3;
一次宣告所有值-
float percentage[] = {56.4 , 99.0, 12.20, 67.2}
1 | 2 | 3 | 4 | #5 | |
56.78 | 99.20 | 12.22 | 87.66 | 34.44 |
float anam’spercentage = percentage[4];
#include <iostream> using namespace std; int main(){ float percentage[] = {56.4 , 99.0, 12.20, 67.2}; cout<<"printing all values of the array :\n"; for(int i = 0; i<4 ; i++){ cout<<"element "<<i+1<<" = "<<percentage[i]<<endl; } return 0; }
printing all values of the array : element 1 = 56.4 element 2 = 99 element 3 = 12.2 element 4 = 67.2
#include <iostream> using namespace std; int main(){ float percentage[4]; percentage[0] = 56.3; percentage[1] = 99.12; percentage[2] = 78.32; percentage[3] = 61.3; cout<<"3rd element is "<<percentage[2]; return 0; }
3rd element is 78.32
#include <iostream> using namespace std; int main(){ float percentage[4]; percentage[0] = 56.3; percentage[1] = 99.12; percentage[2] = 78.32; percentage[3] = 61.3; cout<<"3rd element is "<<percentage[2]; percentage[2] = 12.22; cout<<"\nafter change :\n"; cout<<"3rd element is "<<percentage[2]; return 0; }
3rd element is 78.32 after change : 3rd element is 12.22
以上是C/C++程式中的陣列的詳細內容。更多資訊請關注PHP中文網其他相關文章!