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.
REMEMBER!
NUMBERING OF ARRAYS IN C 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.
#include <iostream>
using namespace std;
main()
{
int i=1, A[5];
A[0] = 23; //to each of the 5 elements of the array (indices 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[i] + 2*A[0] + A[2];
cout << A[2]+A[4];
}
As a result of the execution of this program, the value of the array element with index 2 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
#include<iostream>
using namespace std;
main()
{
const int N = 5;
int A[N];
x = 1;
cout << A[x-3]; //reference to element A[-2]
A[x+4]=A[x]+A[2*(x+1)]; //after substituting x into expressions and calculations, we get the following line: A[5] = A[1]+A[4];
...
}
Because the array is declared with 5 elements, which means the elements will be numbered
from 0 to 4. We see that the program accesses non-existent elements:
A[-2] and
A[5]
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, programs usually crash with
run-time error
Let's try to work with array elements on our own.
Complete the task