Arrays tutorial 1b

Program Comments
//Arrays - Tutorial 1
#include <iostream>
#include <iomanip>

void init           (int [10][10], int, int);
void do_totals      (int [10][10],
                     int [10],
                     int, int);
void display_array  (int [10][10], int, int);
void display_totals (int [10],     int);
Each of the functions is prototyped, ie declared so that the following functions know that these functions exist. You can see that in the prototypes it isn't necessary to name each argument, all that is required is to state each type.
int main()

{ int num[10][10], 
      totals[] = {0,0,0,0,0,0,0,0,0,0};
  int row, column;

  init(num, 10,10);
  do_totals(num, totals, 10,10);
  display_array(num, 10,10);
  display_totals(totals, 10);

  return 0;
} 
In the main function we call each of the subordinate functions in turn.
void init(int n[10][10], int r, int c)
{
 int i,j;

 for (i = 0; i < r; i++) 
  for (j = 0; j < c; j++)
   n[i][j] = i * j;
}
Here the array is initialised. I use the arguments r and c to carry the limits for the two for loops - the row and column for loops.
void do_totals( int n[10][10],
                int t[10],
                int r, int c)
{
 int i,j;

 for (j = 0; j < c; j++)
  for (i = 0; i < r; i++) 
   t[j] = t[j] + n[i][j];
}
The totalling function has two arrays and two integers as its arguments. The n array is the num array and the t array is the totals array.
void display_array (int n[10][10],
                    int r, int c)
{
 int i,j;

 for (i = 0; i < r; i++)
  { cout << "....... "; 
    for (j = 0; j < c; j++)
     cout << setw(4) << n[i][j];
    cout << endl;
  }
}
void display_totals (int t[10], int r)
{
 int i;

 cout << "Totals: ";
 for (i = 0; i < r; i++)
  cout << setw(4)
       << t[i];
 cout << endl;
}
Last of all the totals are shown, after the last row of the num array.

Return to the lesson


Copyright © 1999 - 2001 David Beech