1: // Filename: TWODIMA1.CPP
2: // Purpose: Illustrates declaration, initialization and
3: // processing of a two-dimensional array.
5: #include <iostream>
6: #include <iomanip>
7: using namespace std;
9: int main()
10: {
11: cout << "\nThis program illustrates a two-dimensional array."
12: << "\nStudy the source code and the output simultaneously.\n\n";
14: // Declare *and* initialize a two-dimensional array
15: const NUM_ROWS = 3;
16: const NUM_COLS = 5;
17: int a[NUM_ROWS][NUM_COLS] =
18: { { 2, 4, 6, 8, 10 },
19: { -1, -2 }, // Remaining values in 2nd row will be 0.
20: { 1, 3, 5, 7, 9 }
21: };
23: int row, col; // For use as row and column indices
25: // Display all values in the array:
26: cout << endl;
27: for (row = 0; row < NUM_ROWS; row++)
28: {
29: for (col = 0; col < NUM_COLS; col++)
30: cout << setw(4) << a[row][col];
31: cout << endl;
32: }
34: const int SIZE = 3;
35: int b[SIZE][SIZE];
37: // Initialize a two-dimensional array with nested for loops:
38: for (row = 0; row < SIZE; row++)
39: for (col = 0; col < SIZE; col++)
40: b[row][col] = row + col; // Just some value
42: // Display all values in the array again:
43: cout << endl;
44: for (row = 0; row < SIZE; row++)
45: {
46: for (col = 0; col < SIZE; col++)
47: cout << setw(4) << b[row][col];
48: cout << endl;
49: }
51: // Display values in 2nd row, followed by 3rd columns:
52: cout << endl;
53: for (col = 0; col < SIZE; col++)
54: cout << setw(4) << b[1][col];
55: cout << endl;
56: for (row = 0; row < SIZE; row++)
57: cout << setw(4) << b[row][2];
58: cout << endl;
60: // Display values on main diagonal:
61: for (row = 0; row < SIZE; row++)
62: cout << setw(4) << b[row][row];
63: cout << endl;
65: // Display values on minor diagonal:
66: for (row = SIZE-1; row >= 0; row--)
67: cout << setw(4) << b[row][SIZE-1 - row];
68: cout << endl << endl;
70: return 0;
71: }