home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / mat3.cpp < prev    next >
C/C++ Source or Header  |  1993-03-25  |  2KB  |  78 lines

  1. /*
  2.   C++ program that demonstrates the use of two-dimension arrays.
  3.   The average value of each matrix column is calculated.
  4. */
  5.  
  6. #include <iostream.h>
  7.  
  8. const int MAX_COL = 10;
  9. const int MAX_ROW = 30;
  10.  
  11. int getRows()
  12. {   
  13.   int n;
  14.   // get the number of rows
  15.   do {
  16.     cout << "Enter number of rows [2 to "
  17.          << MAX_ROW << "] : ";
  18.     cin >> n;
  19.   } while (n < 2 || n > MAX_ROW);
  20.   return n;
  21. }
  22.  
  23. int getColumns()
  24. {
  25.   int n;
  26.   // get the number of columns
  27.   do {
  28.     cout << "Enter number of columns [1 to "
  29.          << MAX_COL << "] : ";
  30.     cin >> n;
  31.   } while (n < 1 || n > MAX_COL);
  32.   return n;
  33. }  
  34.  
  35. void inputMatrix(double mat[][MAX_COL], 
  36.                  int rows, int columns)
  37. {
  38.   // get the matrix elements
  39.   for (int i = 0; i < rows; i++)  {
  40.     for (int j = 0; j < columns; j++)  {
  41.       cout << "X[" << i << "][" << j << "] : ";
  42.       cin >> mat[i][j];
  43.     }
  44.     cout << "\n";
  45.   }
  46. }
  47.  
  48. void showColumnAverage(double mat[][MAX_COL], 
  49.                        int rows, int columns)
  50. {
  51.   double sum, sumx, mean;
  52.   sum = rows;
  53.   // obtain the sum of each column
  54.   for (int j = 0; j < columns; j++)  {
  55.     // initialize summations
  56.     sumx = 0.0;
  57.     for (int i = 0; i < rows; i++)
  58.       sumx += mat[i][j];
  59.     mean = sumx / sum;
  60.     cout << "Mean for column " << j
  61.          << " = " << mean << "\n";
  62.   }
  63. }
  64.  
  65. main()
  66. {
  67.     double x[MAX_ROW][MAX_COL];
  68.     int rows, columns;
  69.     // get matrix dimensions
  70.     rows = getRows();
  71.     columns = getColumns(); 
  72.     // get matrix data
  73.     inputMatrix(x, rows, columns);
  74.     // show results
  75.     showColumnAverage(x, rows, columns);
  76.     return 0;
  77. }
  78.