#include #include class matrix { protected: int rows, cols; int * data; public: matrix(int numrows, int numcols) { rows = numrows; cols = numcols; data = new int [rows*cols]; } int numrows() { return rows; } int numcols() { return cols; } protected: int pos(int r, int c) { if (r<0 || r>=rows || c<0 || c>=cols) { cout << "error accessing [" << r << "][" << c << "] when range is " << "[0 to " << rows-1 << "][0 to " << cols-1 << "]\n"; return -1; } return r * cols + c; } public: int get(int r, int c) { int p = pos(r, c); if (p == -1) return 0; return data[p]; } void set(int r, int c, int newval) { int p = pos(r, c); if (p == -1) return; data[p] = newval; } }; void print(matrix & M) // ALWAYS use a reference parameter for any object that { int rows = M.numrows(), // anything created by "new". cols = M.numcols(); for (int r = 0; r < rows; r += 1) { for (int c = 0; c < cols; c += 1) cout << " " << setw(3) << M.get(r, c); cout << "\n"; } } void main() { matrix timestable(12, 12); for (int x = 1; x <= 12; x += 1) for (int y = 1; y <= 12; y += 1) // be careful: arrays run from 0 to max, but timestable.set(x-1, y-1, x*y); // times-tableses go from 1 to 12. cout << "Behold the times-table\n\n"; print(timestable); cout << "\nThat's that.\n"; }