In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. Arrays are used to store and manipulate data that is related in some way, such as a list of numbers, a set of strings, or a collection of objects.
Declare an Array
To declare an array in C++, you need to specify the data type of the elements in the array, the name of the array, and the number of elements in the array. Here’s an example of how to declare an array of integers with 5 elements:
int myArray[5];
This creates an array called myArray
with 5 integer elements. Note that the elements of the array are numbered starting from 0, so the first element is myArray[0]
, the second element is myArray[1]
, and so on.
Initialize Elements
You can also initialize the elements of an array when you declare it. Here’s an example of how to declare and initialize an array of integers:
int myArray[] = {1, 2, 3, 4, 5};
This creates an array called myArray
with 5 integer elements, initialized with the values 1, 2, 3, 4, and 5.
Access an Element
Once you’ve declared an array, you can access its elements using the subscript operator []
. Here’s an example of how to access the third element of myArray
:
int thirdElement = myArray[2];
This assigns the value of the third element (which has an index of 2) to the variable thirdElement
.
Assign Values
You can also assign values to elements of an array using the subscript operator. Here’s an example of how to set the fourth element of myArray
to the value 10:
myArray[3] = 10;
This sets the value of the fourth element (which has an index of 3) to 10.
You can iterate over the elements of an array using a loop, such as a for
loop. Here’s an example of how to iterate over the elements of myArray
and print their values:
for (int i = 0; i < 5; i++) { std::cout << myArray[i] << " "; }
This prints the values of the elements of myArray
separated by spaces.
Arrays can also be used to store and manipulate more complex data types, such as strings or objects. In those cases, the array elements would be of the appropriate data type (e.g., std::string
for a string array, or a class name for an object array).