次のプログラムでは、prices と呼ばれる浮動小数点配列を定義します。
最初の for ステートメントは、prices のエレメントの値を印刷します。 2 番目の for ステートメントは、prices の各エレメントの値に 5 % を加算し、total にその結果を割り当て、これらを total として印刷します。
/** ** Example of one-dimensional arrays **/ #include <stdio.h> #define ARR_SIZE 5 int main(void) { static float const prices[ARR_SIZE] = { 1.41, 1.50, 3.75, 5.00, .86 }; auto float total; int i; for (i = 0; i < ARR_SIZE; i++) { printf("price = $%.2f¥n", prices[i]); } printf("¥n"); for (i = 0; i < ARR_SIZE; i++) { total = prices[i] * 1.05; printf("total = $%.2f¥n", total); } return(0); }
このプログラムの出力は次のようになります。
price = $1.41 price = $1.50 price = $3.75 price = $5.00 price = $0.86 total = $1.48 total = $1.57 total = $3.94 total = $5.25 total = $0.90
次のプログラムでは、多次元配列 salary_tbl を定義します。 for ループでは、salary_tbl の値が印刷されます。
/** ** Example of a multidimensional array **/ #include <stdio.h> #define ROW_SIZE 3 #define COLUMN_SIZE 5 int main(void) { static int salary_tbl[ROW_SIZE][COLUMN_SIZE] = { { 500, 550, 600, 650, 700 }, { 600, 670, 740, 810, 880 }, { 740, 840, 940, 1040, 1140 } }; int grade , step; for (grade = 0; grade < ROW_SIZE; ++grade) for (step = 0; step < COLUMN_SIZE; ++step) { printf("salary_tbl[%d] [%d] = %d¥n", grade, step, salary_tbl[grade] [step]); } return(0); }
このプログラムの出力は次のようになります。
salary_tbl[0] [0] = 500 salary_tbl[0] [1] = 550 salary_tbl[0] [2] = 600 salary_tbl[0] [3] = 650 salary_tbl[0] [4] = 700 salary_tbl[1] [0] = 600 salary_tbl[1] [1] = 670 salary_tbl[1] [2] = 740 salary_tbl[1] [3] = 810 salary_tbl[1] [4] = 880 salary_tbl[2] [0] = 740 salary_tbl[2] [1] = 840 salary_tbl[2] [2] = 940 salary_tbl[2] [3] = 1040 salary_tbl[2] [4] = 1140
関連参照