211: Programming For IS 1 --- Lecture Nov. 12

Topics:

Implementing Lists using Arrays
Input and output of Lists
Passing Arrays as Functions

Implementing Lists using Arrays

An important application of an array is to implement a list, e.g., a list of students in a class. It is natural to store the list in the first N positions of the array where N is the size of the list, i.e., positions 0 through N-1. In addition to the array we must maintain a variable which keeps track of the size of the list.

CAUTION: Do not confuse the size of the array which is fixed with the size of the list which may vary.

For example, suppose that we declared an array GradeList[] as follows:

int GradeList[200];

Depending on the number of students in the class the size of the list will vary from 1 to 200, and the list will be stored in positions 0 through Size - 1 of GradeList[], where Size is an integer variable that maintains the size of the class. The list elements can be input into the array GradeList[] as follows:

for(int Position = 0; Position < Size; ++Position)
{
   cout << "Enter list element: ";
   cin >> GradeList[Position]
}//END for
The list can be displayed as follows:
for(int Position = 0; Position < Size; ++Position)
{
   cout << GradeList[Position] << '\t';
}//END for
Passing Arrays as Functions

To pass an array to a function you must pass the address of the array. In C++ the array name is the address of the first element of the array. Since the array name references the address of the array the array is automatically passed by reference.

Consider the function GetGrades below, which inputs a list of grades. Grades are input into an array until a negative number (sentinel) is encountered. Note that, unlike with the parameter Size, there is no ampersand (&) preceding the parameter GradeList[]. This is because GradeList[] is an array and as such is automatically passed by reference.

void GetGrades(int GradeList[],int &Size)
{
      int Grade;
      //READ IN FIRST GRADE 
      cout << "Enter grade or negative value to stop: ";
      cin >> Grade;
      Size = 0;
      while(Grade >= 0)
      {
         GradeList[Size] = Grade;  //ADD GRADE TO ARRAY
         ++Size;  //UPDATE SIZE

         //READ IN NEXT GRADE
         cout << "Enter grade or negative value to stop: ";
         cin >> Grade;
      }//END while
  }//END GetGrades()
The following function computes the average of elements in a list. Note that since the parameter Size is to remain unchanged by Average(), it is passed by value. Since the parameter List[] is an array it is automatically passed by reference.
float Average(float List[], int Size)
{
   float Sum = 0.0;
   for(int Count=0; Count < Size; ++Count)  //COMPUTE SUM OF LIST ELEMENTS
      Sum += List[Count]; 
   return Sum/Size;
}//END Average()