Two-dimensional arrays are declared by specifying the data type, variable name, number of rows, and number of columns, e.g.
const int ROWS = 3; const int COLS = 4; float myTable[ROWS][COLS];Access to elements is by specifying row and column, e.g.
To define them as part of a parameter list, the array must use empty square
brackets for the rows, and include the size of the column field. It is
often useful to pass the number of rows you wish processed as an additional
parameter, e.g.
void fillArray(float arr[][COLS], int numRows);
A full version is shown below:
#include <cstdio> const int ROWS = 3; const int COLS = 4; void fillArray(float arr[][COLS], int numRows); int main() { float myTable[ROWS][COLS]; fillArray(myTable, ROWS); return 0; } void fillArray(float arr[][COLS], int numRows) { for (int r = 0; r < numRows; r++) { for (int c = 0; c < COLS; c++) { printf("Enter the value for row %d", r); printf(", column %d\n", c); scanf("%g", &arr[r][c]); } } } |
Exercises: