RECORDS/1 In an array, all of the data items have to belong to the same data type. If mixed data types need to be stored then parallel arrays need to be used. Another data structure that can handle mixed data types is a record and in many cases this provides a better solution than parallel arrays. A record is made up of fields. In pascal a record is set up as follows: type planet = record name : string; howfar : integer end;
In the above example planet is the name of the record structure, name and howfar are field names in the record. So each record has two fields. This is the structure of a single record which we can now use as a userdefined type: var solar : planet We now have a variable that can hold data about a single planet. We access the individual fields by what is known as dot notation. solar.name = ‘earth’ If we wish to output the contents of a record then we can write: writeln(solar.name) A complete program might look like this: program set_up_a_record uses crt; type planet = record name : string; howfar : integer end; var solar : planet; begin clrscr; solar.name = ‘earth’; solar.howfar = 93; writeln(‘DATA ON PLANETS’) writeln; writeln(‘Planet name : ‘, solar.name); writeln(‘Distance from sun :’, solar.howfar); end.
RECORDS/2 A shorthand method of notating the record structure is to use the keyword with. e.g. with solar do begin name := ‘earth’; howfar := 93 end;
In the above examples the program only stored one record. To create a structure that can hold more records we can create an array of records. To do this we need to employ a second type definition and create an array of several elements whose underlying data structure is that of planet as shown below: type planet = record name : string; howfar : integer end; solarsystem = array[1..9] of planet; We can now declare the array in the var section: var planetdata : solarsystem; planetdata is a variable with nine elements each of which has two fields, name and howfar. i.e. planetdata name 1 ‘MERCURY’ 2 ‘VENUS’ 3 ‘EARTH’ 4 ‘MARS’ 5 ‘JUPITER’ 6 ‘SATURN’ 7 ‘URANUS’ 8 ‘NEPTUNE’ 9 ‘PLUTO’
howfar 58 108 50 228 778 1427 2869 4498 5900
To output the second field of the third record we could write the following: writeln(planetdata.howfar);
Now, move to the pascal document on Pointers.