ARRAYS in Turbo Pascal - Part 1

Arrays may be declared in TYPE or VAR statements. They must be declared in TYPE statements in order to be used in a procedure or function's formal parameter list. You may think of arrays as "lists" of components which are all of exactly the same kind. The general syntax is:
Array_id: ARRAY [Start .. End] OF Components
where the Start .. End are values of any legal ordinal type and the components are any data type except TEXT. Examples:
Type
  Grades = Array [1..5] of Integer;
  Alpha_counters = Array ['a' .. 'z'] of Integer;
  Names = Array [1..4] of String[30];
  List = Array [1..100] of 1..100;
  Avg_list = Array [1..50] of Real;
  Flag_list = Array [1..10] of Boolean;
To obtain storage of these kinds, use the appropriate Var statement:
Var
  X, Y: Grades;
  Z: Alpha_counter;
  Location: Integer;
  Alpha: 'a'..'z';
The READ and WRITE procedures cannot be used with structured types like arrays, so that statements like READ(X) and WRITELN(Y) are illegal and will cause an error at compile time. To read entries into the array X, use a FOR loop:
For Location := 1 to 5 Do
  Readln(X[Location]);
To "zero out" the array Z, use a FOR loop:
For Alpha := 'a' to 'z' Do
  Z[Alpha] := 0;
To write all the values of the array, similarly use a FOR loop:
For Alpha := 'a' to 'z' Do
  Writeln(Alpha, ' = ', X[Location]);
To write just a few elements in the array, use their position in the array:
Writeln('The first and third entries in the list are: ', X[1], X[3]);
Pascal does allow the assignment statement to be used between arrays of exactly the same kind. For example, the statement Y := X; is legal in Pascal and takes the place of the FOR loop:
For Location := 1 to 5 Do
  Y[Location] := X[Location];

Forward to next page Forward to
Page 2
on Arrays
    Return to
CS-171
Home Page
    Return to
UW-W
Home Page
   
This page last updated
19 May 2000