Tags:
create new tag
view all tags

2-Dimensional Array Hands on Learning Activity

Objectives:

  • To be able to declare a two-dimensional array.
  • To be able to perform fundamental operations on a two-dimensional array.
  • To be able to pass two-dimensional arrays as parameters.
  • To be able to view a two-dimensional array as an array of array

Introduction to Two-Dimensional Arrays

Two-dimensional arrays, the most common multidimensional arrays, are used to store information that we normally represent in table form. Two-dimensional arrays, like one-dimensional arrays, are homogeneous. This means that all of the data in a two-dimensional array is of the same type. Examples of applications involving two-dimensional arrays include:

  • a seating plan for a room (organized by rows and columns),
  • a monthly budget (organized by category and month), and
  • a grade book where rows might correspond to individual students and columns to student scores.

Declaration of Two-Dimensional Arrays

Example: The following array declarations set aside storage for a two-dimensional array called labScores which contains 40 rows and 14 columns. Rows correspond to a particular student and columns correspond to a particular lab score.

const int MAX_STUDENTS=40;
const int MAX_LABS=14;
int labScores [MAX_STUDENTS][MAX_LABS];

In Class Exercise 1:

Show C++ statements to declare the following two-dimensional array:

Declare a two-dimensional array which can be used to store a yearly budget. Each row of the array corresponds to a particular budgeted item like rent, electric, etc. There are at most 15 items to be budgeted. Each column of the array corresponds to a month, January, February, etc. Of course there are 12 columns corresponding to the 12 months of the year. All the data to be placed in the array consists of real numbers.

Solution


Manipulation of a two-dimensional array requires the manipulation of two indices. When the two-dimensional array labScores is declared, enough storage is set aside to hold a table containing 40 rows and 14 columns for a total of 40 * 14 = 560 integer values. To access one particular value, we must specify the row and column. The row index ranges from 0 to MAX_STUDENTS-1 (39) and the column index ranges from 0 to MAX_LABS-1 (13). Thus the table can be visualized as:


L14array1.gif

This two-dimensional array may also be visualized as a one-dimensional array of arrays. An alternative view of this array would be:

L14array2.gif

This two-dimensional array may be viewed as a one-dimensional array having 40 elements where each element is an array of 14 values.

Accessing a Two-Dimensional Array Element

In our labScores example, suppose we wish to indicate that the second student (corresponding to row 1) made a 90 on lab 10 (corresponding to column 9). We might use the statement:

labScores [1][9] = 90;


Array indices may be integer constants (as in the above example), variables, or expressions. They should be within the bounds of the array.

Two-Dimensional Array Initialization

We can declare and initialize an array A as follows:

</sticky>

//declaration int A[3][4] = {{8, 2, 6, 5}, //row 0 {6, 3, 1 ,0}, //row 1 {8, 7, 9, 6}}; //row 2
</sticky>
Memory for the array may be visualized as:

L14memory.gif

Hands on Exercise 2:

  1. What value is stored in row index 2, column index 1?
  2. Give the name of the location where the value 0 is stored?
  3. Show the order of the elements as ordered in actual memory.
Solution

We may also initialize a 2-D array by reading data. Suppose we wish to read entries into our labScores array. We should use two loops--one to control the student (row) and one to control the lab (column). To read in all labs corresponding to the first student, then read in all labs corresponding to the second student, and so on, we might use the following function:

//Function:    ReadScores()
//Purpose:     This function inputs lab scores for
//             students in a computing class.
//

void ReadScores(int labScores [MAX_STUDENTS][MAX_LABS], //OUT: student labs
                int& numStudents,                       //OUT: actual # of students
                int& numLabs);                           //OUT: actual # of labs
{
   //local variables
   int student, lab;        //index for the student and lab being processed

   //first read the number of students and labs
   cout << "Enter the number of students followed by the number of labs:";
   cin >> numStudents >> numLabs;

   //Outer loop controls which student (row) is being read
   for (student = 0; student < numStudents; student++)
   {
       //Inner loop controls which lab (column) is being read
       for (lab = 0; lab < numLabs; lab++)
           cout  << "Enter score for student " << student << " lab " << lab << ":";
           cin >> labS [student][lab];
   }
   return;
}

In Class Exercise 3:

Enter the code above into NetBeans, create a main function that defines the array and constants, and calls the ReadScores routine. Get it working.

Now suppose we wish to read in the data for our students' scores but the input is organized differently. Instead of all of one student's labs being entered first, the all grades for lab 1 are entered first, then all grades on lab 2, etc. How must the code above be changed to accommodate this new strategy of inputs? Change the code and get it running?

Two-Dimensional Arrays as Function Parameters

As with one-dimensional arrays, a two-dimensional array is automatically passed as a pass-by-reference parameter. Consider the function heading above. The following function heading also could have been used:

void ReadScores (int labScores[][MAX_LABS],      //OUT: student labs
                    int& numStudents,               //OUT: Number of students
                    int& numLabs);                   //OUT: Number of labs 

Notice the difference between these two function headings. For the labsScores array, the second heading does not include the number of rows required by the array but does include the number of columns. The explanation is simple -- when we pass an array the compiler need only know the size of its elements, not how many elements it has. As explained above, a two-dimensional array can be thought of as a one-dimensional array of elements (which just happen to be arrays themselves). Thus the compiler needs to know the size of one of the elements. Each element is a row of values so the compiler needs to know the type of elements and how many values (the number of columns) are in each row. In the labScores array, the number of columns is MAX_LABS.

If one wants to print the entire set of scores, a nested loop similar to that above can be used.

Hands on Exercise 4:

Write a routine "DisplayScores(...)" that displays the scores in rows and columns. What are in the parameters? Test out the code on NetBeans.

 Student 1: 80 90 70 100 60 90 85 78 93 80 70 98 89 94
 Student 2: 98 85 100 99 89 90 72 0 78 98 100 65 0 56
 Student 3: 85 60 25....

Two-Dimensional Array Processing

Processing of two-dimensional arrays might include finding an average of a row or a column. Suppose in our lab scores problem, we wish to determine the lab average for the third student (remember, this means row 2). The solution to this problem consists of finding the sum of all of the entries in row index 2 and dividing by the number of labs, NUM_OF_LABS.

Two-Dimensional Array Processing Processing of two-dimensional arrays might include finding an average of a row or a column. Suppose in our lab scores problem, we wish to determine the lab average for the third student (remember, this means row 2). The solution to this problem consists of finding the sum of all of the entries in row index 2 and dividing by the number of labs, NUM_OF_LABS.

sum = 0;
    student = 2; // 3rd student
    for (lab = 0; lab < NUM_OF_LABS; lab++) {
         sum += labScores[student][lab];
           }
    average = float(sum)/NUM_OF_LABS;
    cout << "The average for student " << student+1 << " is " 
    << average << endl;

In general, if we wished to determine the average for the Kth student, then K-1 would replace the value 2 in statement 16 above. If we wished to find an average for all 40 students, we can add an outer loop to control the student index.

Hands on Exercise 5:

Add a function to your program, StudentsAvg (....), which finds and prints the lab average for each student in the class. A function prototype for this function is shown below. Activate this function from the main program. Compile and run your program.

void StudentsAvg(int labScores [][MAX_LABS],  //IN:  Lab scores
                   int numStudents,             //IN:  # of students in the class
                   int numLabs)                 //IN:  # of labs recorded per student

In order to write this function, make use of another simpler function, SudentAvg (...), which is passed a student index, and it computes the average for that student:

double StudentAvg(int labScores [][MAX_LABS],  //IN:  Lab scores
                   int numStudents,             //IN:  # of students in the class
                   int numLabs,                 //IN:  # of labs recorded per student
                   int student) ;                  //IN:  # of student to get average for

Hands on Exercise 6:

Add a function to cla14a.cc, say LabAvg (), which finds and prints the average score made on each individual lab. Activate this function from the the main program. Compile and run your program.

Topic attachments
I Attachment History Action Size Date Who Comment
GIFgif L14array1.gif r1 manage 3.3 K 2018-02-21 - 16:34 JimSkon  
GIFgif L14array2.gif r1 manage 2.6 K 2018-02-21 - 16:35 JimSkon  
GIFgif L14memory.gif r1 manage 3.5 K 2018-02-21 - 16:38 JimSkon  
Topic revision: r1 - 2018-02-21 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback