Parallel arrays past paper question

Parallell arrays ppq

(a) (i)
Without arrays you would need to have separate variables for each value, which would be confusing and error-prone. It is very easy to change the values in an array by using an index value, e.g. averages[5] = 80.

(ii)

MAX = 0
loop J from 0 to NUMSTUDENTS - 1
  if AVERAGES[J] > MAX then
    MAX = AVERAGES[J]
    NAME = STUDENTS[J]
  end if
end loop
output NAME

(b) (i)
The arrays are aligned such that STUDENTS[N] has an average of AVERAGES[N].
If only one of the arrays is sorted, then this alignment will be lost and it will no longer be possible to tell which student has which average.
If one array is sorted, then the other array needs to be sorted in the same way.

(ii)

loop J from 0 to NUMSTUDENTS - 1
  loop K from 0 to NUMSTUDENTS - 1
    if AVERAGES[K] < AVERAGES[K+1] then
      TEMPA = AVERAGES[K]
      AVERAGES[K] = AVERAGES[K+1]
      AVERAGES[K+1] = TEMPA
      TEMPS = STUDENTS[K]
      STUDENTS[K] = STUDENTS[K+1]
      [K+1] = TEMPS
    end if
  end loop
end loop

(c)
A student object could be created, with two member variables, “name” and “average”.
These variables would be bound to the object and so could not be separated.
You could then have one array of student objects, which would be more manageable than having two arrays that have to be kept aligned.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s