An array is a collection of elements of the same data type stored in contiguous memory locations. Arrays help you store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, specify the data type, array name, and size (number of elements) inside square brackets []
.
data_type array_name[array_size];
int numbers[5]; // declares an array of 5 integers
You can initialize an array during declaration by providing a list of values inside curly braces {}
.
int numbers[5] = {10, 20, 30, 40, 50};
If you provide fewer values than the size, the remaining elements are initialized to zero.
int arr[5] = {1, 2}; // arr = {1, 2, 0, 0, 0}
Access elements of an array using the index inside square brackets. Note that array indices start at 0.
int numbers[5] = {10, 20, 30, 40, 50}; cout << numbers[0]; // Outputs: 10 cout << numbers[3]; // Outputs: 40
You can assign a new value to any element by accessing it via its index.
numbers[2] = 100; // Change the 3rd element (index 2) to 100
You can iterate through array elements using loops, commonly a for
loop.
for(int i = 0; i < 5; i++) { cout << "Element " << i << ": " << numbers[i] << endl; }
std::array
and std::vector
for safer and dynamic arrays (advanced topics).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!