Problem

2/9

Accessing an array element

Theory Click to read/hide

Referring to an array element.< /u>

Most 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 particular array element.

Remember: C# array numbering starts at zero.< br />
Examples of accessing the array A:
int x = (A[3] + 5) * A[1] / / read values ​​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.
int i = 1;
int[] A = new int[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];
Console.Write((A[2] + A[4]));

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

Let's analyze an example program.
int N = 5;
int[] A = new int[N];
int x = 1;
A[x + 4] = A[x] + A[2 * (x + 1)];  // after substituting x into expressions and calculations 
                          // get the next line A[5] = A[1] + A[4]
                          // A[5] no such element exists
                          // error - out of bounds array

The array is declared with 5 elements, which means that the elements will be numbered from 0 to 4. We see, that the program in the 6th line refers to a non-existent element: A[5].
It turns out that the program has gone beyond the bounds of the array.
An array overrun is an access to an element at an index that does not exist in the array.
In such cases, the program usually crashes with a run-time error.

 

Problem

In lines 9 through 12, set the array elements at index 1 to 4 to be twice the value the previous element of the array. 
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 record
A[1] = 46 will be considered invalid.