Source of twodima2.cpp


  1: // Filename: TWODIMA2.CPP
  2: // Purpose:  Illustrates passing a two-dimensional array as a parameter.

  4: #include <iostream>
  5: #include <iomanip>
  6: using namespace std;

  8: void FindMaxRowVals(/* in */  const int a[][5],
  9:                     /* out */ int maxRowVals[],
 10:                     /* in */  int numRows);

 12: int main()
 13: {
 14:     cout << "\nThis program illustrates passing a "
 15:          << "two-dimensional array as a function "
 16:          << "\nparameter.  Study the source code "
 17:          << "and the output simultaneously.\n\n";

 19:     int a[3][5] = { {  2,  4,  6,  8, 10 },
 20:                     { -1, -2 },
 21:                     {  7,  9,  5,  1,  3 }
 22:                   };

 24:     int maxValues[3];

 26:     FindMaxRowVals(a, maxValues, 3);

 28:     int row;
 29:     cout << endl;
 30:     for (row = 0; row < 3; row++)
 31:     {
 32:         cout << "The maximum value in row "
 33:              << row << " is " << maxValues[row] << "." << endl;
 34:     }
 35:     cout << endl;

 37:     return 0;
 38: }


 41: void FindMaxRowVals(/* in */  const int a[][5],
 42:                     /* out */ int maxRowVals[],
 43:                     /* in */  int numRows)
 44: // Pre:  "a" and "numRows" have been initialized.
 45: // Post: "maxRowVals" contains the maximum values in the rows of "a",
 46: //       with the maximum value in row 0 of the (two-dimensional) array
 47: //       "a" in component 0 of the (one-dimensional) array "maxRowVals",
 48: //       and so on for the other rows of "a" and "maxRowVals".
 49: {
 50:     int row, col, max;
 51:     for (row = 0; row < numRows; row++)
 52:     {
 53:         max = a[row][0];
 54:         for (col = 1; col < 5; col++)
 55:         {
 56:             if (a[row][col] > max)
 57:                 max = a[row][col];
 58:         }
 59:         maxRowVals[row] = max;
 60:     }
 61: }