C++ Array Basics
Overview
In this tutorial, we will learn C++ Array Basics. An array is a collection of data items of the same type. Each item in an array is stored one after the other in the memory. i.e., contiguous memory locations.
Declare an Array
We can declare an array of six integers as shown below:
int marks[6] = {95, 58, 91, 72, 84, 53};
The above array is a single-dimensional array or 1-D array. The address of the array is the address of its first element.
Access Array elements
Array index starts with 0. We can access the array elements with the index as shown below:
For example, to access the first array element, we can use:
marks[0]
Let’s assume that the first element of the array is stored at 1024 memory address. The int data type occupies 4 bytes of memory. So, the second element of the array would be stored at 1028, and so on.
The number of array elements is 6. The array index ranges from 0 to 5. The size of the array in memory is:Â sizeof(marks)
would be 6×4 = 24 bytes.
Example
Sample C++ program to declare an array and print the array elements.
/************************************ * C++ Array * Filename: arithmetic.cpp * C++ Array Demo program. * C++ Tutorials - www.TestingDocs.com **************************************/ #include using namespace std; int main() { //Declare an array int marks[6] = {95, 58, 91, 72, 84, 53}; cout << marks[0] << endl ; cout << marks[1] << endl ; cout << marks[2] << endl ; cout << marks[3] << endl ; cout << marks[4] << endl ; cout << marks[5] << endl ; return 0; } // end main
Output
—
C++ Tutorials
C++ Tutorials on this website:
https://www.testingdocs.com/c-coding-tutorials/
For more information on the current ISO C++ standard