Array
An array is a data structure that contains a group of elements of the same data type and stores them together in contiguous memory locations. Computer programmers use arrays in their programs to organize sets of data in a way that can be easily sorted and searched. They are more efficient at storing data than separate variables and can help a program run faster.
Arrays are a very versatile method of storing data in a program. For example, a search engine may use an array to save a list of search results. It can display one element from that array at a time, in sequence, until it reaches either a specified number of results or the final value stored in the array. Since these values are all stored in one large block of memory instead of in separate variables stored in multiple locations, the results are shown quickly and efficiently.
Since an array stores its values in contiguous memory locations, the size of an array is set when created. The data type, like integer or string, is also defined at creation. A program can reference individual values in an array using the array name combined with that value's index address. In most languages, the index starts with 0 and increments from there. However, some languages start the index at 1, while others allow the programmer to choose whether an index starts with 0 or 1.
Creating and Using an Array
The syntax in C++ for creating an array and storing values in it looks like this:
int characterStats[6] = {15, 14, 13, 12, 10, 8};
The int statement sets the data type as integer, and characterStats gives the array a name. The square brackets [] specify that it is an array, while the number inside the brackets determines its length. The values in the curly brackets {}, separated by commas, are the values contained in the array.
The syntax for displaying a specific value in an array may look like this:
print(characterStats[2]);
Since this array's index starts with 0, this statement would output the number 13, the array's third value. Programmers may also use while and for loops with arrays to output multiple values from an array in sequence with a single command.