Data Structures
Data Structures
Introduction
The data types explained so far are all predefined in the language and are called simple data types, as opposed
to structured data types. Each datum of a simple data type is one single element, while in structured types (such
as arrays) a datum may contain a collection of items. Simple types fall into two main categories:
The ordinal type
The real type
Ordinal Data Types
The ordinal types include the INTEGER, CHAR, and BOOLEAN types. An ordinal type is distinguished by
data values that form a series of discrete elements such that every element has a discrete predecessor (except the
first element) and successor (except the last element). Integers are like that, as they form a set of distinct
numbers ranging from -(MAXINT+1) to +MAXINT. The element “4,” for example, is preceded by “3” and
followed by “5.” The type CHAR includes a set of characters ordered sequentially according to their ordinal
numbers. The type BOOLEAN contains the set “TRUE and FALSE.” The value FALSE has the ordinal number
“0” while TRUE has the ordinal number “1.” Real numbers, on the other hand, are not discrete. For example,
between the number “0” and “1” there exists an infinite number of fractions. Between any two real numbers,
then, there is another real number.
Arrays, files records and files are referred to as structured data types because they can be used to represent data
values that have a structure of some sort. Structured data types provide an organizational scheme that shows the
relationships among the individual elements and facilitate efficient data manipulations. These structured data
types are called data structures.
Enumerations
Pascal provides another method -- a programmer-defined type called an enumerated type. This is a set of integer
constants that are represented by identifiers, the usual alphanumeric ones used for variables. The type is
declared as an ordinal list in the type section such as the following one for the days of the week.
It is sometimes useful in a program to define days of the week as integers in order to make the program code
more readable. In this case, you need to either assign each day a number or to declare each a named constant as
in:
CONST
Monday = 0;
Tuesday = 1;
Wednesday = 2;
Thursday = 3;
Friday = 4;
Saturday = 5;
Sunday = 6;
Internally, the values start with the zeroth item, so Monday is equivalent to 0 and Sunday to 6 in the above
example. After these declarations you can refer to any of these days by its name:
1
IF Today = Sunday THEN
WRITELN('Sorry, we are closed on Sundays..');
In this statement an integer variable “Today” is tested to check if it is “Sunday”; in other words, if it contains
the value “6.” Using such declarations will take a lot of programming effort, though, especially when you have
a large number of constants (such as the names of the months). The enumerated type gives you a shortcut to
doing the same thing. Look at the following declaration:
VAR
Day :( Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
In this declaration, the identifiers representing the months are listed in an ordered series and separated by
commas. Thus, Monday is internally coded as “0” and “Sunday” is coded as “6.” Other days are represented by
numbers between “0” and “6” according to their sequence in the enumeration. It is, however, illegal to read or
write these values directly as you do with simple types (using WRITELN and READLN statements). With
enumerations you may use any of the following operations:
1. You may assign any one of the enumeration elements to the variable “Day” like this:
Day:= Friday;
but it is illegal to assign an explicit number to the variable “Day,” such as “Day:= 1.” This feature assures
that the enumeration will be only assigned valid data.
2. You can obtain and use the values associated with the enumeration elements using the ORD function. For
example:
WRITELN(ORD(Monday)); gives the value "0"
WRITELN(ORD(Tuesday)); gives the value "1"
3. You may also use the functions PRED and SUCC to obtain the predecessor and the successor of a specified
element:
WRITELN(PRED(Friday)); gives the value "3"
WRITELN(SUCC(Monday)); gives the value "1"
4. You can compare values of the enumerated type using the Boolean operators (simple or compound), like
this:
IF (Day = Saturday) OR (Day = Sunday) THEN
WRITELN('This is a weekend day.');
Again, you cannot use the explicit values in comparisons such as “IF Day = 2.” This results in an error.In the
following program a FOR loop uses the enumeration “Month” to display the corresponding integer values from
“0” to “11.”
PROGRAM Enumeration1(INPUT,OUTPUT);
VAR
Month:(Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);
BEGIN
WRITELN;
FOR Month:= Jan TO Dec DO
WRITE(ORD(Month),' ')
END.
The output of this program is:
0 1 2 3 4 5 6 7 8 9 10 11
2
As you can see in the output, the values that correspond to the twelve months range from “0” to “11.” If you
would like to see the values range from “1” to “12” as the months in the calendar do, you can use the expression
“ORD(month)+1” instead of the expression “ORD(month).” The enumerated type is an ordinal data type and is
classified as a user-defined type.
Subranges
The so-called subrange types belong to the ordinal types as well. They are declared by constraining the sets of
values of already introduced ordinal types. A subrange type represents a subset of the values in another ordinal
type (called the base type). Any construction of the form Low..High, where Low and High are constant
expressions of the same ordinal type and Low is less than High, identifies a subrange type that includes all
values between Low and High. For example, if you declare the enumerated type
TYPE Colors = (Red, Blue, Green, Yellow, Orange, Purple, White, Black);
you can then define a subrange type like
TYPE MyColors = Green..White;
Here MyColors includes the values Green, Yellow, Orange, Purple, and White. You can use numeric constants
and characters (string constants of length 1) to define subrange types.
3
ARRAYS
An array is a data structure which holds many variables all of the same data type. An Array is a powerful data
structure that stores variable data having the same data type. It is just like a small fixed number of boxes linked
together one after the other storing things that are related to each other. Arrays are used just like ordinary
variables. They are used to store typed data just like the ordinary variables. You will now learn how to assign
data to arrays and read data from arrays.
scores is the identifier for this array which can hold up to 100 integer values. Individual elements are accessed
using the identifier and a subscript, which must be one of a range of ordinals. Here the ordinal (integer)
subscripts range from 1 to 100. This array can be diagrammed as follows:
4
Value 55 74 ... 56 52
Subscript 1 2 ... 99 100
Component scores[1] scores[2] . . . scores[99] scores[100]
Name
To assign the value 74 to the second element in the array, you could use the following statement.
scores[2] := 74;
Initializing all of the values to zero is a simple matter:
FOR i := 1 to 100 DO
scores[i] := 0;
To find the sum of all of the values in the array, the following would suffice:
sum := 0;
FOR i := 1 to 100 DO
sum := sum + scores[i];
To be useful, however, unless the array is always full, we must either use one of the elements as an end-of-list
marker or keep a count in another variable. Here we will look at the latter technique using the following
variable.
num_scores : integer;
Again arrays must be declared as a variable before it can be used I.e. the data declaration of :
VAR
one, two, three four, five, six: INTEGER
can be replaced by
CONST
MaxValue=6;
VAR
Frequency: ARRAY [1 .. MaxValue] of INTEGER
This informs the compiler of an array structure named frequency that contain six data cells numbered 1 through
6 i.e. [1 .. MaxValue] the content of each cell is an item of data of type integer. When referencing the contents
of an array Frequency only the indices 1,2,3,4,5 & 6 are legal in denoting the position of the cell. Calculations
done must be consistent with the data type that has been declared as integer.
Sample program
This is a program which initializes an array of integer scores with 5 values and then finds and prints the highest
score.
PROGRAM FindHighest (INPUT, OUTPUT);
VAR
scores : ARRAY [1..100] OF INTEGER;
num_scores : INTEGER;
high_score : INTEGER;
i: INTEGER;
BEGIN
{ initialize counter }
num_scores := 0;
5
{Initialize array & count elements }
scores[1] := 55;
num_scores := num_scores + 1;
scores[2] := 74;
num_scores := num_scores + 1;
scores[3] := 45;
num_scores := num_scores + 1;
scores[4] := 88;
num_scores := num_scores + 1;
scores[5] := 67;
num_scores := num_scores + 1;
{ initialize high_score }
high_score := scores[1];
{ report findings }
WRITE ( high_score, ' is the highest score out of ');
FOR i := 1 TO num_scores - 1 DO
WRITE ( scores[i], ', ');
WRITELN( 'and ', scores[num_scores], '.')
END.
The following Pascal program reads and store the scores of five students in one subject, then display the output
as shown below:
Student # Score
-----------------
1 90.00
2 88.00
3 91.00
4 78.00
5 75.00
-----------------
Average score = 84.40
PROGRAM Scores4(INPUT,OUTPUT);
CONST
NumberOfStudents = 5;
Tab = ' '; { 9 spaces }
Dash = '-';
NumberOfDashes = 23;
VAR
Score: ARRAY[1..NumberOfStudents] OF REAL;
Average, SumOfScores :REAL;
Index :INTEGER;
BEGIN
{ Read the scores array }
{ --------------------- }
FOR Index := 1 TO NumberOfStudents DO
BEGIN
WRITE('Enter Score of Student #', Index,': ');
READLN(Score[Index])
END;
{ Calculate the average score }
6
{ --------------------------- }
SumOfScores := 0;
FOR Index := 1 TO NumberOfStudents DO
SumOfScores := SumOfScores + Score[Index];
Average := SumOfScores / NumberOfStudents;
{ Display Results }
{ --------------- }
WRITELN;
WRITE(Tab, 'Student #');
WRITE(Tab, 'Score');
WRITELN;
WRITE(Tab);
FOR Index := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
FOR Index := 1 TO NumberOfStudents DO
WRITELN(Tab,Index:3,tab,Score[Index]:10:2);
WRITE(Tab);
FOR Index := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
WRITELN(Tab,'Average score = ', Average:0:2);
WRITELN;
END.
Two-dimensional arrays
Two dimensional arrays and multi –dimensional arrays store variables in second or nth dimension having N by
M storage location.To declare a two-dimensional array, use the form:
VAR
Array_name: ARRAY [index_range_1, index_range_2] OF Data_type;
You may also declare it in the type section as follows:
TYPE
Type_name = ARRAY [index_range_1, index_range_2] OF Data_type;
7
where “index-range1” (the number of rows) and “index-range2” (the number of columns) are the ranges of the
first and second dimensions.
Look at this declaration:
TYPE
Score = ARRAY [1..100, 1..6] OF INTEGER;
This statement declares an array “Score,” which can store the scores of 100 students in six different classes;
generally speaking, it can store up to 600 integers. As you can see, each dimension is represented by a subrange.
You can also declare a multidimensional array of any number of dimensions using the general form:
TYPE
Type_name = ARRAY [index_range_1, index_range_2, ... ,
index_range_n] OF Data_type;
In most applications, however, you will not need more than two dimensions.
Sample 3 by 5 array
Let us declare an array having 3 by 5 dimensions, assign values to all variables in the array and illustrate this on
a table.
10 57 72 34 78
90 44 54 12 32
99 19 77 76 50
After the declaration we now assign data to all the array elements as shown in the table. Note that during data
assignment to respective array elements row and column number need to be passed into the array name and
enclosed in square brackets
BEGIN
SampleArray[1,1]:=10;
SampleArray[1,2]:=57;
SampleArray[1,3]:=72;
SampleArray[1,4]:=34;
SampleArray[1,5]:=78;
SampleArray[2,1]:=90;
SampleArray[2,2]:=44;
SampleArray[2,3]:=54;
SampleArray[2,4]:=12;
SampleArray[2,5]:=32;
SampleArray[3,1]:=99;
SampleArray[3,2]:=19;
SampleArray[3,3]:=77;
SampleArray[3,4]:=76;
SampleArray[3,5]:=50;
END.
Scores of Students
8
The following program is used to read the scores of a number of students in different classes as represented in a
Table. For simplicity of demonstration, only four students and three Subjects will be considered; you can,
however, modify the number of students or classes by simply changing the values of the two constants
“NumberOfSubjects” and “NumberOfStudents.”
PROGRAM Scores3(INPUT,OUTPUT);
{ using two-dimensional array }
CONST
NumberOfSubjects = 3; { Change this number for more classes }
NumberOfStudents = 4; { Change this number for more students }
Tab = ' '; { 7 spaces }
Dash = '-';
NumberOfDashes = 23;
TYPE
ScoreArray = ARRAY [1..NumberOfStudents, 1..NumberOfSubjects] OF
REAL;
AverageArray = ARRAY [1..NumberOfStudents] OF REAL;
VAR
Score :ScoreArray;
Average :AverageArray;
SumOfScores :REAL;
StudentCount, ScoreCount, DashCount: INTEGER;
BEGIN
{ Read the scores array }
{ --------------- }
FOR StudentCount:= 1 TO NumberOfStudents DO
BEGIN
WRITELN;
WRITELN ('Scores of student #', StudentCount,': ');
FOR ScoreCount:= 1 TO NumberOfSubjects DO
BEGIN
WRITE ('Enter score for Subject #', ScoreCount,': ');
READLN (Score[StudentCount, ScoreCount])
END;
END;
{ Calculate the average for each student }
{ --------------------------- }
FOR StudentCount:= 1 TO NumberOfStudents DO
BEGIN
SumOfScores:= 0; { Initialize for each student }
FOR ScoreCount:= 1 TO NumberOfSubjects DO
SumOfScores:= SumOfScores + Score[StudentCount, ScoreCount];
Average[StudentCount]:= SumOfScores/NumberOfSubjects
END;
{ Display results }
{ ------------ }
WRITELN;
WRITELN(Tab, 'Student #', Tab, 'Average');
WRITE(Tab);
FOR DashCount:= 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
FOR StudentCount:= 1 TO NumberOfStudents DO
WRITELN(Tab, StudentCount:3, Tab, Average[StudentCount]:12:2);
WRITE(Tab);
FOR DashCount:= 1 TO NumberOfDashes DO
WRITE(Dash);
9
WRITELN;
END.
Student # Average
----------------
1 90.67
2 70.00
3 81.67
4 93.33
----------------
The following table shows the above sample run scores in a two dimensional array:
90 89 93
80 70 60
77 78 90
91 94 95
10
The exact location of the array element is determined by the two indexes “StudentCount” and
“ScoreCount.”
3. The average of scores is calculated for each student and stored in the array variable:
Average[StudentCount]
The index “StudentCount” indicates which student has each average.
4. Notice the initialization of the variable “SumOfScores” before the average calculation. This is a very
important step because if it is not done, the average of the previous student will remain in the variable and
be added to the new average.
Array initialization
If you are assigning values to only some of the elements of an uninitialized array, do not expect that the rest of
the elements will contain zeros. In such applications you have to initialize the whole array using a loop like this:
FOR I:= 1 TO N DO
MyArray[I]:= 0;
You need another loop if the array is two-dimensional:
FOR I:= 1 TO N DO
FOR J:= 1 TO M DO
MyArray[I,J]:= 0;
In the last example, we assigned values to each element of the array, so there was no need for initialization.
Sample program
The following two-dimensional array accept four students scores of three subjects and display the students’
names in descending order according to their scores, as in this example:
Student name Average
-----------------
Porter, Thomas 84.00
Dalton, Jack 83.33
Dixon, Jane 83.33
Bobbin, Dale 66.67
-----------------
The Program
PROGRAM Scores6(INPUT,OUTPUT);
{ Using two-dimensional array }
CONST
NumberOfSubjects = 3; { Change this number for more Subjects }
NumberOfStudents = 4; { Change this number for more students }
Tab = ‘ ‘ { 5 spaces }
Dash = '-';
NumberOfDashes = 23;
TYPE
ScoreArray = ARRAY [1..NumberOfStudents, 1..NumberOfSubjects] OF
REAL;
AverageArray = ARRAY [1..NumberOfStudents] OF REAL;
NameArray = ARRAY [1..NumberOfStudents] OF STRING;
VAR
Score :ScoreArray;
Average :AverageArray;
Name :NameArray;
SumOfScores, AveragePot :REAL;
StudentCount, ScoreCount, DashCount :INTEGER;
11
I, J :INTEGER;
NamePot :STRING;
BEGIN
{Read the scores array }
{ --------------------- }
FOR StudentCount := 1 TO NumberOfStudents DO
BEGIN
WRITELN;
WRITE ('Name of student #', StudentCount,': ');
READLN (Name[StudentCount]);
WRITELN ('Scores of ', Name[StudentCount], ': ');
FOR ScoreCount := 1 TO NumberOfSubjects DO
BEGIN
WRITE ('Enter score of Subject #', ScoreCount,': ');
READLN (Score[StudentCount, ScoreCount])
END;
END;
{ Calculate the average for each student }
{ -------------------------------------- }
FOR StudentCount := 1 TO NumberOfStudents DO
BEGIN
SumOfScores:= 0; { Initialize for each student }
FOR ScoreCount := 1 TO NumberOfSubjects DO
SumOfScores := SumOfScores + Score[StudentCount,
ScoreCount];
Average[StudentCount] := SumOfScores/NumberOfSubjects
END;
{ Sort averages in a descending order }
{ ------------------------------------ }
FOR I := 1 TO NumberOfStudents-1 DO
BEGIN
FOR J := I+1 TO NumberOfStudents DO
IF Average[J] > Average[I] THEN
BEGIN
{ swap the averages }
AveragePot := Average[I];
Average[I] := Average[J];
Average[J] := AveragePot;
{ swap the corresponding student number }
NamePot := Name[I];
Name[I] := Name[J];
Name[J] := NamePot
END { End of IF and inner loop }
END; { End of outer loop }
{ Display results }
{ --------------- }
WRITELN;
WRITELN(Tab, 'Student name', Tab, 'Average');
WRITE(Tab);
FOR DashCount := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
FOR StudentCount := 1 TO NumberOfStudents DO
BEGIN
WRITE(Tab, Name[StudentCount]);
FOR I := 1 TO 15 - LENGTH(Name[StudentCount]) DO
WRITE(' ');
WRITELN(Average[StudentCount]:8:2)
END;
12
WRITE(Tab);
FOR DashCount := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
END.
Summary
In this chapter you have had a review of simple and structured data types.
1. You now know that simple data types are classified as either “real” or “ordinal” types. Of the ordinal types,
you learned how to use the user-defined types, enumerations and subranges.
2. You learned how to use the TYPE statement to declare a new type or rename a predefined type. It takes the
general form:
TYPE
type-name = type-definition;
In standard Pascal the relative sequence of the TYPE section among the other sections in the declaration part
is as follows:
LABEL section
CONST section
TYPE section
VAR section
3. You learned about the array as a predefined structured data type that may be declared either in the TYPE
section or VAR section. You also learned how to declare and use both one- and two-dimensional arrays.
The general form to declare an array of any number of dimensions (in the TYPE section) is:
TYPE
type-name = ARRAY[index-range-1, index-range-2, ..., index-range-n] OF element-
type;
13