#include <iostream> #include <iomanip> using namespace std; int main() { const int NUM_MONTHS = 12; int days[NUM_MONTHS]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July days[7] = 31; // August days[8] = 30; // September days[9] = 31; // October days[10] = 30; // November days[11] = 31; // December for (int month = 0; month < NUM_MONTHS; month++) { cout << "Month "<< setw (2) << (month+1) << " has "; cout << days[month] << " days.n"; } return 0; }程式輸出結果:
Month 1 has 31 days.
Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.
int days [NUM_MONTHS] = {31,28,31,30,31,30,31,31,30,31,30, 31};
這些值按照它們出現在列表中的順序儲存在陣列元素中(第一個值 31 儲存在 days[0] 中,第二個值 28 儲存在 days [1] 中,等等)。圖 1 顯示了初始化後陣列的內容。