The text presented the first version of multtab in Chapter 3 to demonstrate nested for-loops. Adding arrays to the program doesn't enhance its functionality, but it demonstrates two-dimensional arrays in a familiar context. The following programs define a 12×12 two-dimensional array named table, fill it 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, while the second 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, making them INOUT arguments, allowing data to move in both directions.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int table[12][12]; // [rows] [cols] // (a)
for (int row = 1; row <= 12; row++) // (b)
for (int col = 1; col <= 12; col++)
table[row - 1][col - 1] = row * col |
![]() |
row*col. However, C++ arrays are zero-indexed, forcing the program to offset the (b) for-loops: table[row - 1][col - 1].
When functions define multi-dimensional array parameters, they can omit the size of the first dimension, but must specify the size of the second and subsequent dimensions. This requirement results from how C⁠++ organizes and locates array elements in memory. (See Row-Major Ordering later in the chapter.) The following figure illustrates both notations with the multiplication table array.
| Prototype | Comments |
|---|---|
| void multtab(int tab |
The function and the client calling it "agree" on the number of rows and columns in advance. |
| void multtab(int tab |
The function and the client calling it "agree" on the number of columns, but the function can operate on any number of rows if the client provides the number. |
| Fixed Number Of Rows | Variable Number Of Rows |
|---|---|
#include <iostream> #include <iomanip> using namespace std; void fill_table(int tab |
#include <iostream> #include <iomanip> using namespace std; void fill_table(int tab |