Open main menu

Wikibooks β

Pascal Programming/Arrays

< Pascal Programming

Lists, or Arrays are types in Pascal that can be used to store multiple data using one variable.

Static Size ArraysEdit

These lists are defined in syntax of:

type MyArray1 = array[0..100] of integer;

type MyArray2 = array[0..5] of array[0..10] of char;
type MyArray2 = array[0..5,0..10] of char;

Examples of this would be having a list of different types or records.

type my_list_of_names = array[0..7] of string;

var the_list: my_list_of_names;

  the_list[5] := 'John';
  the_list[0] := 'Newbie';

This would create an array of ['Newbie','','','','','John','','']. We can access these variables the same way as we have set them:

  writeln('Name 0: ', the_list[0]);
  writeln('Name 5: ', the_list[5]);

The following example shows an array with indices of chars.

  a: array['A'..'Z'] of characters;
  s: string;
  i: byte;

  readln(s); {reads the string}
  for i := 1 to length(s) do {executes the code for each letter in the string}
    if upcase(s[i]) in['A'..'Z'] then
      inc( a[upcase(s[i])] );
    {counts the number the times a letter is counted. the case doesn't count}
  writeln('The number of times the letter A appears in the string is ',a['A']);
  {returns 5 if the string is 'Abracadabra'} 

Dynamic ArraysEdit

Lists also can contain unlimited number of items, depending on the amount of computer memory. This is acheived by dynamic arrays, which appeared with Delphi (not available with Turbo Pascal). To declare a dynamic array, simply declare an array without bounds :

var a: array of <element_type>;

Then, define the size at any moment with the function SetLength

SetLength( a, <New_Length> );

The indices of the array will from 0 to length(a)-1.

You can get the current length with the Length function, as for String type. To go through the array, you can write for example :

  i: integer;
  a: array of integer;
  setlength(a, 10); { a will contain 10 random numbers }
  for i := 0 to length(a)-1 do
    a[i] := random(10)+1;

The memory is freed automatically when the array is not used anymore, but you can free it before by assigning nil value to the variable which is the same as defining a length of 0.