Data storage
Let's say you've developed a computer game called "User Hostile" in which the players compete against an intricate and unfriendly computer interface. Now you need to write a program that tracks the monthly sales of this game over a five year period. Or let's say you need to inventory Hacker Hero Trading Cards.
Very soon you will come to the conclusion that you need more than simple basic data types to store and process information.
Arrays (lists). Introduction
In order to make it convenient to work with a large amount of data, a group of cells is given a common name. Such a group of cells is called an
array
Array – it is a group of memory cells of the same type, located side by side and having a common name. Each cell in the group has a unique number.
When working with arrays, you need to
learn how to solve three tasks:
x allocate memory of the required size for an array
x write data to the desired cell
x read data from cell
Arrays in Pascal
Traditionally Pascal uses static arrays like
var a: array [1..10] of integer;
The boundaries of an array must be set by constants, and you cannot change the size of an array during program operation. But you can make an index not only of an integer, but also, say, of a character or enumerated type. For example, to count the occurrence of each letter, you can use an array
var LettersCount: array ['a'..'z'] of integer;
and work with it to your heart's content:
LettersCount['z'] := 1;
LettersCount['d'] := LettersCount['d'] + 1;
The disadvantages of such arrays are known: if it is not known in advance how many elements will need to be used, then the maximum size memory is allocated for the array. As a result, in most cases we "stock up for the future", and sometimes this "reserve" turns out not to be enough. That is why such arrays are called static: their size is static and must be set at the program compilation stage. However, in Pascal there are dynamic arrays, the size of which can not only be set, but also changed in the course of the program. It is these arrays and the advantages of using them that will be discussed further.
Creating an array
When creating an array, space is allocated in memory (a certain number of cells)
1) Arrays can be created by simply listing the elements:
var a: array of integer;
SetLength(a, 3);
a[0] := 1;
a[1] := 2;
a[2] := 3;
2) Arrays can be composed of data of any type - integer or real numbers, character strings
var a: array of char;
SetLength(a, 3);
a[0] := 'a';
a[1] := 'b';
a[2] := 'c';
3) An array always "knows" your size. The
length
function is used to determine the size of an array. Often the size of the array is stored in a separate variable so that the program can be easily changed to work with a different array size. Example:
N := 10; // in the variable N we store the size of the array
SetLength(a, N); // set array and size N
writeln(length(a)); //display the size of the array
The size of an array can be set from the keyboard.