Arrays
We use arrays to store many objects of one type. We create them using this pattern: "type of variables that will be stored in this array - name - size;" (int a[4];
). An array index is the position number used to access or reference a specific element within an array, starting from 0. To get to the address of the first element of an array, we can write only the array's name (instead of &a[0]
). When we create an array, an appropriate amount of memory "in a row" is reserved (the amount required for a given data type times the size), but the values that were there don't vanish. To set them as zeros, we can write: int a[4] = {0};
. We can also assign all the values at the beginning: int tab3[4] = {1, 2, 3, 4};
or int tab3[] = {1, 2, 3, 4};
. An array cannot contain elements that have different data types.
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
cout << "a[0] equals " << a[0] << " and has the address " << &a[0] << endl;
cout << "a[1] equals " << a[1] << " and has the address " << &a[1] << endl;
cout << "a[2] equals " << a[2] << " and has the address " << &a[2] << endl;
cout << "a[3] equals " << a[3] << " and has the address " << &a[3] << endl;
for (int i = 0; i < 4; i++) // iterating over an array (accessing every single array element independently)
cout << a[i] << endl;
We can create multidimensional arrays (an array in an array, etc.) A two-dimensional array is called a matrix. To access an element from the internal array, we do as in the example below. The first index means which array we are entering, and the second index means which element of the internal array we want to access.
int a[4]; // container for 4 variables
int a1[4][3]; // 4 containers (0, 1, 2, 3) that can store 3 variables (0, 1, 2). Overall, it can store 4*3 = 12 variables.
a1[0][1] = 5;
cout << a1[0][1] << endl;
int a2[2][3][2]; // 2 containers that can store 3 other containers, which can store 2 variables. Overall, it can store 2*3*2 = 12 variables.
a2[1][2][1] = 6;
cout << a2[1][2][1] << endl;
// Defining the array's elements in a loop
int a[100];
for (int i = 0; i < 100; i++) {
a[i] = i;
cout << "a[" << i << "] = " << a[i] << endl;
}
cout << sizeof(a) / sizeof(a[0]) << endl; // array's size (length)