Parallel Arrays
It is not possible to use a two-dimensional array to store different types of data. We often want to associate data items with different data types, such as a surname (string) with a mark (integer) for an individual. This can be achieved by using the data structure called a record (to be covered later) or by using parallel arrays. In these parallel arrays, the properties of an individual will be located using the same value of the index in each array. To find a mark for an individual, the surname is searched for in the array of string to find the index, which is then used to obtain the mark from the array of integer.
program GetMark; {$APPTYPE CONSOLE} const MAX = 4; var Surnames : array[1..MAX] of string; Marks : array[1..MAX] of integer; Count, SearchMark : integer; SearchName : string; Found : Boolean; begin for Count := 1 to MAX do begin write('Please enter surname ', Count, '. '); readln(Surnames[Count]); write('Please enter the mark for ', Surnames[Count], '. '); readln(Marks[Count]); end; write('To obtain a mark, please enter the surname. '); readln(SearchName); Count := 0; Found := false; repeat inc(Count); if Surnames[Count] = SearchName then begin Found := true; end; until Found or (Count = MAX); if Found then begin SearchMark := Marks[Count]; writeln('Mark for ', SearchName, ': ', SearchMark); end else begin writeln(SearchName, ' not found.'); end; readln; end.
Features introduced:
- Parallel arrays of string and integer
- Linear search of array
- Use of constant as upper bound of the array so that it can be changed easily
- Use of Boolean variable as a flag
- Use of “if Found then” instead of “if Found = TRUE then”
- Use of inc to increment a variable