An array is a data structure collection object that contains multiple variables. The variables contained in an array are called elements of the array, and are accessed by their computed indexed indices. C++ arrays are indexed using the zero index approach, meaning that the first element in the array has an index value of 0, the second element has an index value of 1, the third element has an index value of 2, and so on and so forth, and incrementing sequentially until the end of the array.
All of the elements of an array must be of the same variable data type. For example, if you have an array of int
variables then every element of that array must be on an integer data type. If you have an array of string
variables then every element of that array must be of a string data type.
To create an array, define the variable type using square brackets:
string animals[];
The above example declared a variable named "animals" that holds an array of strings.
There are various ways to assign values to an array. One way to insert values into the array, is to use the array literal by placing the values in a comma-separated list, inside curly braces, and assigning it to the variable during declaration:
string animals[] = {"cat" , "dog" , "bird" , "fish" };
Another example, we could create an array of integers as follows:
int myIntArray[] = {3 , 8 , 12 , 44 , 7 , -19 , 533 , 0 , -28 , 8 , 8 , 8 , 52 };
It is often more useful to create an array of empty values, and then assign values to the arrays elements later:
int myIntArray[7 ];
myIntArray[0 ] = 3 ;
myIntArray[1 ] = 8 ;
myIntArray[2 ] = 12 ;
myIntArray[3 ] = 44 ;
myIntArray[4 ] = 7 ;
myIntArray[5 ] = -19 ;
myIntArray[6 ] = 533 ;
The above example creates an integer array that has 7 empty elements of integer variable data type. It then assigns the values of each element by accessing that element using its index value and then assigning an integer value to it.
int scores[5];
(which has index values from 0 through 4) and yet you try to read or assign a value of scores[5]
, then you may accidentally overwrite values in memory for some other variable, which will result in some kind of miscalculation, bug, or error, and which may or may not cause a system error. Even if it did result in a system error, or even a complete computer crash, the error might not manifest itself until some time later, which can make it difficult to troubleshoot.You can access the value stored within an array element by referring to the index number of that element. Once you access that element, you can either read that elements variable value and/or assign a new value to that elements variable (as long as you do not try and change the variable type of that element):
// create an int array and assign values to it
int myIntArray[] = {3 , 8 , 12 , 44 , 7 , -19 , 533 , 0 , -28 , 8 , 8 , 8 , 52 };
// read the 6th element of the array and output its value to the console
cout << myIntArray[5 ] << "\n" ; // outputs -19
// assign a new value to the 6th element of the array
myIntArray[5 ] = 7 ;
// read the 6th element of the array and output its value to the console
cout << myIntArray[5 ] << "\n" ; // outputs 7
To find out how many elements an array has, use the sizeof
property to calculate it:
// create a string array and assign values to its elements
string animals[] = {"cat" , "dog" , "bird" , "fish" };
// create an integer variable and assign the Length of the animals array to it
int tempLength = sizeof (animals) / sizeof (animals[0 ]);
// output the length value to the console window
cout << tempLength << "\n" ; // outputs 4
This divides the total size of the array (in bytes) by the size of one element, giving you the number of elements. It's fast, clean, and doesn't require iterating through loops, nor does it require knowing what the arrays data type is.
There may be times when your program needs to loop through the elements of an array. There are various ways to loop through an array, and you are able to loop from any element index to any other element index within that array, or you can loop from the first element of that array to its last element, or last to first.
The following is an example of looping through an array using the for
loop method, and loops from the first element of the array to the last element of the array:
// create a string array and assign values to its elements
string animals[] = {"cat" , "dog" , "bird" , "fish" };
// create an integer variable and assign the Length of the animals array to it
int tempLength = sizeof (animals) / sizeof (animals[0 ]);
// loop through each element of the array from index 0 (which is the first element of the array) to the last element of the array
for (int i=0 ; i < tempLength; i++)
{
// output the element value to the console window
cout << animals[i] << "\n" ;
}
With the for
method, it is possible to loop just a portion of the array instead of the entire array by specifying which index values to loop through:
// create a string array and assign values to its elements
string animals[] = {"cat" , "dog" , "bird" , "fish" };
// loop through each element of the array from index 1 to 3
for (int i=1 ; i < 3 ; i++)
{
// output the element value to the console window
cout << animals[i] << "\n" ;
}
There is also the for-each
loop, which is used exclusively to loop through elements in an array (and other data structures also, such as vectors and lists):
// create a string array and assign values to its elements
string animals[] = {"cat" , "dog" , "bird" , "fish" };
// Loop through the elements and output their value
for (string i : animals){
cout << i << "\n" ;
}
The array examples listed above are known as Single Dimension Arrays, or a 1-D array. If you were to view the data of the 1-D array in a tabular form (such as in a data grid or Excel spreadsheet), then it would look like a single column of data that has multiple rows. In this 1-D array, each row represents a single element, and the array of elements is the single column of rows.
Multi Dimension Arrays are arrays of arrays. One way to mentally visualize them is as follows: a 2-D array would look like a single spreadsheet that has multiple columns, where each column has the same number of rows, and the element would be the cell located at X (column) and Y (row). A 3-D array would look like a stack of multiple spreadsheets contained within one workbook, where each spreadsheet has multiple columns and rows of cells. A 4-D array would look like a stack of multiple workbooks where each workbook contains multiple spreadsheets that have multiple columns and rows of cells in each. A 5-D array would look like a shelf which contains multiple workbooks sitting on it. A 6-D array would look like a book shelf that has multiple shelves of workbooks. A 7-D array would look like a room that has multiple book shelves. A 8-D array would look like a building that has multiple rooms filled with multiple bookshelves in each. A 9-D array would look like a city that has multiple buildings. A 10-D array would look like a state that has multiple cities. A 11-D array would look like a continent that has multiple states. A 12-D array would look like a planet with multiple continents. A 13-D array would look like a solar system with multiple planets. A 14-D array would look like a galaxy with multiple solar systems in it. A 15-D array would look like a section of the universe that has multiple galaxies in it. And so on, and so forth. Figuratively speaking, of course. In reality, they are nothing more than arrays within arrays of variables.
Although it is possible to create as many dimensions as you want, it is not practice, because your computer would very quickly run out of memory. This is because each element is a variable of a data type. Variables of data types have and use a fixed amount of memory (2 bytes, 4 bytes, 16 bytes, 32 bytes, 64 bytes, etc.. per variable : per array element). A single dimension array is a collection of elements, and a multi dimension array is a collection of arrays. Therefore, the larger the collection is, the more memory all of those elements collectively require and consume, regardless of if you assign a value to them or not.
A 2-D array (or 2D array, however you prefer to describe it) is one of the most commonly used multi-dimensional array. The best way to visualize 2-D arrays is to think of an Excel spreadsheet. The array contains an X and Y index value, which points to the element (i.e. to the spreadsheets cell). 3D arrays are commonly used as matrices.
The following is an example of creating a 2D array:
int grid[3 ][4 ]; // 3 rows, 4 columns
This creates a matrix with 12 elements total.
The following is another example of initializing a 2D array and accessing its elements:
// Create and initialize a 2D array
int matrix[2 ][3 ] = {
{1 , 2 , 3 },
{4 , 5 , 6 }
};
// Access and print elements
for (int row = 0 ; row < 2 ; row++) {
for (int col = 0 ; col < 3 ; col++) {
cout << "matrix[" << row << "][" << col << "] = " << matrix[row][col] << "\n" ;
}
}
int cube[2 ][3 ][4 ]; // 2 layers, 3 rows, 4 columns
To access the elements of a 3D array:
int cube[2 ][3 ][4 ] = {
{ // Layer 0
{1 , 2 , 3 , 4 }, // Row 0
{5 , 6 , 7 , 8 }, // Row 1
{9 , 10 , 11 , 12 } // Row 2
},
{ // Layer 1
{13 , 14 , 15 , 16 }, // Row 0
{17 , 18 , 19 , 20 }, // Row 1
{21 , 22 , 23 , 24 } // Row 2
}
};
// output the value of an element
cout << cube[0 ][1 ][2 ]; // outputs 7
The above outputs 7 because cube[0]
is Layer 0, cube[0][1]
is Row 1 of Layer 0, and cube[0][1][2]
is the third element of Row 1 of Layer 0, which as a value of 7.
You can create and have any number of dimensions. Just keep in mind that the more dimensions an array has, the more complex the code becomes.
Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.
About | Contact Us | Privacy | Terms & Conditions | © 2025 - T&J Divisions, LLC, All Rights Reserved |