Let’s continue our side quest in the world of coding by talking about arrays. Arrays are a quite important concept, since they allow coders to store more than one value into a single variable.
Let’s dive in!
What is an array?
An array is basically a fixed-size container that stores multiple elements of the same type.
Declaring an array is very similar to declaring a simple variable; first the type must be specified (i.e. int
), then the name of the variable (i.e. numbers
) and finally its size between squared brackets (i.e. [5]
):
int numbers[5];
The array can also be initialized during declaration:
int number[5] = { 3, 5, 2, 1, 7};
We can think of an array as a sequence of blocks, with each block containing a specified value, as in the picture below.
Accessing an array
How can we access the values stored into an array? To do that, we have to access it using the array index. The index underlines the position that each elements has inside the array itself.
Quick question, in a 5-element array, which are the possible indices with which we can access the elements?
If you answer was “0-4”, well good job, you are right! In fact, the first element of an array has index “0
”, the second one “1
” and so on. In general, an array of size N
has indices ranging from 0
to (N-1
).
The syntax to access an element is quite straightforward:
numbers[0];
Taking into consideration the previous example:
// Accessing first array element and printing it
std::cout << “The first element is: “ << numbers[0] << std::endl;
This line of code will print: “The first element is: 3”.
Modifying an array
Once an array has been created, it is possible to modify it very easily. In fact, the only thing that has to be done is accessing our array element and assign a value to it.
Let’s say we want to modify the third element of our numbers
array; the syntax is the following:
numbers[2] = 9;
What happens is shown in the following image:
The third element, which previously had value “2
”, has been modified to “9
”.
Aaaaaand we are good to go for today! Thank you for your attention, I hope this helps in having a better chance to understand the Bitcoin code. Please, leave a comment with any suggestion, question or doubt you have!
Btw, next week I will resume the classical IBC post; during the summer I haven’t been very constant, but I promise I will be on time in the following weeks!
Thank you again
Usque ad finem.
Tuma