The text presented the first version of multtab in Chapter 3 to demonstrate nested for-loops. The following versions introduce a 12×12 two-dimensional array named table. They fill table by rows with a 12×12 multiplication table and print it to the console, demonstrating the two-dimensional array syntax. The first version defines, fills, and prints the array in main. The second version defines the array in main but passes it to functions that fill and print it, demonstrating how to pass a two-dimensional array as function arguments. Arrays are always passed by pointer, meaning they are INOUT function arguments - data can move in both directions. Finally, recall that an array's name is its address.
When a program passes an array with two or more dimensions to a function, the function can omit the size of the first dimension but must specify the sizes of the second and subsequent dimensions:
Both versions have their respective advantages and disadvantages. Version 1 is easy to use, requiring only the array parameter. However, it can only operate on a completely filled 12×12 array. We can implement version 2 in two ways. First, it can assume the array has 12 rows, making it similar to version 1 but more vague - a reader seeing the function's prototype is unaware that the number of rows is fixed. Alternatively, we can add a second parameter specifying the number of rows. This approach has the advantage that the function can operate on arrays with any number of rows or partially filled arrays with empty rows at the bottom.
Fixed Number Of Rows | Variable Number Of Rows |
---|---|
#include <iostream> #include <iomanip> using namespace std; void fill_table(int table[][12]); void print_table(int table[][12]); int main() { int table[12][12]; // rows x cols // (a) fill_table(table); // (b) print_table(table); // (c) return 0; } void fill_table(int table[][12]) // (d) { for (int row = 1; row <= 12; row++) for (int col = 1; col <= 12; col++) table[row - 1][col - 1] = row * col; } void print_table(int table[][12]) // (e) { for (int row = 0; row < 12; row++) { for (int col = 0; col < 12; col++) cout << setw(4) << table[row][col]; cout << endl; } } |
#include <iostream> #include <iomanip> using namespace std; void fill_table(int table[][12], int nrows); void print_table(int table[][12], int nrows); int main() { int table[12][12]; // rows x cols // (a) fill_table(table, 12); // (b) print_table(table, 12); // (c) return 0; } void fill_table(int table[][12], int nrows) // (d) { for (int row = 1; row <= nrows; row++) for (int col = 1; col <= 12; col++) table[row - 1][col - 1] = row * col; } void print_table(int table[][12], int nrows) // (e) { for (int row = 0; row < nrows; row++) { for (int col = 0; col < 12; col++) cout << setw(4) << table[row][col]; cout << endl; } } |