Two Dimensional Arrays: Row and Column Processing

Declarations (constants are declared globally):

   const int NUMROWS = 100;
   const int NUMCOLS = 100;
   int table[NUMROWS][NUMCOLS];

Row Processing: Print the Array in Row Order

void printbyrow(int table[][NUMCOLS])
{
   int i, j;
   for (i = 0 ; i < NUMROWS ; i++)
   {
      cout << "Row " << i << ": ";
      for (j = 0 ; j < NUMCOLS ; j++)
         cout <<  table[i][j] << "  ";
      cout << endl;
   }
}

Column Processing: Print the Array in Column Order

void printbycol(int table[][NUMCOLS])
{
   int i, j;
   for (j = 0 ; j < NUMCOLS ; j++)
   {
      cout << "Column " << j << ": ";
      for (i = 0 ; i < NUMROWS ; i++)
         cout <<  table[i][j] << "  ";
      cout << endl;
   }
}

Row Processing: Sum One Row of the Array

int sumrow(int table[][NUMCOLS], int row)
{
   int total = 0;
   int j;
   for (j = 0 ; j < NUMCOLS ; j++)
      total += table[row][j];
   return total;
}

Column Processing: Sum One Column of the Array

int sumcol(int table[][NUMCOLS], int col)
{
   int total = 0;
   int i;
   for (i = 0 ; i < NUMROWS ; i++)
      total += table[i][col];
   return total;
}

Row Processing: Add up Each Row

void addrows(int table[][NUMCOLS])
{
   int i, j, total;
   for (i = 0 ; i < NUMROWS ; i++)
   {
      total = 0;
      for (j = 0 ; j < NUMCOLS ; j++)
         total += table[i][j];
      cout << "The sum of row " << i << " is " << total << endl;
   }
}

Column Processing: Add up Each Column

void printbycol(int table[][NUMCOLS])
{
   int i, j, total;
   for (j = 0 ; j < NUMCOLS ; j++)
   {
      total = 0;
      for (i = 0 ; i < NUMROWS ; i++)
         total += table[i][j];
      cout << "The sum of column " << j << " is " << total << endl;
   }
}

This was taken from a handout by Prof Simon.


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002