Arrays (or vectors) in C++ are data structures that allow storing a collection of elements of the same type.
data_type array_name[size];
#include
using namespace std;
int main()
{
int array[10]; // Declares an array of 10 elements of type int
return 0;
}
We can imagine the array declared above like this (element values are arbitrary):
We say that each element has an index. The indices of an array range from 0 to Size-1, so in our example from 0 to 9.
Accessing an element is done using the indexing operator, [], which has the highest priority. For example:
X[0], X[5], X[i]
Here X is the array identifier (name), and 0, 5, or i are the indices. It is essential for the programmer (that's YOU!) to ensure that the index value is within the correct range for the given array (in our example, between 0 and 9).
Traversing an array means accessing each element of the array in a specific order. Accessing the element is done using the index with the help of the indexing operator.
The following example declares an array with 100 elements and stores the value 1 in the first n elements of the array. As we already know, n must satisfy the relationship n<=100. Otherwise, the program's behavior becomes unpredictable - it is very likely that the operating system will terminate its execution.
int X[100], n;
//n = .... ;
for(int i = 0 ; i < n ; i ++)
X[i] = 1;
Usually, array traversal is done in ascending order of indices, from 0 to n-1. By analogy with the number line, we can say that traversal is done from left to right. The array can also be traversed from right to left, i.e., in descending order of indices, from n-1 to 0:
for(int i = n - 1 ; i >= 0 ; i --)
X[i] = 1;
int X[100], n;
Actually, in most cases, reading a one-dimensional array (vector) cannot be done, i.e.,:
cin >> X;
The above instruction usually leads to a syntax error. Instead, the elements of the array can be read in order using traversal:
cin >> n;
for(int i = 0 ; i < n ; i ++)
cin >> X[i];
int X[100], n;
Similarly to reading, in most cases, displaying an array cannot be done either, i.e.,:
cout << X;
The elements of the array can be displayed by traversal, in the desired order:
for(int i = 0 ; i < n ; i ++)
cout << X[i] <<" ";
Or
for(int i = n - 1 ; i >= 0 ; i --)
cout << X[i] <<" ";
In this section you can generate a summary of the page content using AI! Feel free to use the button below whenever you are in a hurry and don't have time to learn everything!
In this section you can ask our expert robot anything related to the questions you encountered during the lessons! Feel free to use the button below whenever you need additional explanations!