Problem

2/10

Accessing an array element

Theory Click to read/hide

Referencing an array element

Much of the usefulness of arrays comes from the fact that its elements can be accessed individually.
The way to do this is to use an index to number the elements.
Index is a value that points to a specific array element

REMEMBER!
NUMBERING OF ARRAYS IN PASCAL STARTS FROM ZERO!

(This is mandatory — you must start from scratch. This is especially important to remember)

Examples of accessing array A:
x := (A[3] + 5) * A[1] // read the values ​​of A[3] and A[1]
A[0] := x + 6 // write new value to A[0]
Let's analyze the program for working with array elements.
var i: integer;
a: array of integers;

begin
    i := 1;
    setlength(a, 5); //create an array of 5 elements 
    a[0] := 23; // to each of the 5 elements of the array (indexes from 0 to 4)
    a[1] := 12; // write a specific value
    a[2] := 7;
    a[3] := 43;
    a[4] := 51;
    a[2] := a[i] + 2 * a[i - 1] + a[2 * i]; // change the value of the element with index 2 to the result of the expression
    // because i=1, then substituting the value of the variable i into the expression we get
    // next expression  a[2] := a[1] + 2*a[0] + a[2];
    writeln(a[2] + a[4]);
end.


As a result of running this program the value of the sum of the elements of the array with index 2 and with index 4 equal to 116 will appear on the screen. As you can see from the example, we can access any element of the array. And also calculate the required number of the element using various formulas (for example, as in the program A[i-1] or A[2*i], in these cases, the indexes of the elements will be calculated and depend on the value of i.)

Let's look at an example program
var a: array of integer;

begin
    setlength(a, 5);
    a[5] := 5;
    a[-1] := 0;
end.

Because the array is declared with 5 elements, so the elements will be numbered from 0 to 4. We see that the program in the 6th line refers to a non-existent element а [5] and on the 7th line to the also non-existent a[-1].

It turns out that the program went beyond the bounds of the array
Array out of bounds is accessing an element with an index that does not exist in the array.
In such cases, the program usually crashes with run-time error


 
 

Problem

On lines 8 through 11, set the array elements at index 1 to 4 to twice the value of the previous array element. 
In this task, you cannot assign specific numbers, you must refer to the previous element of the array by name and index
That is, the entry a[1] = 46 will be considered incorrect.