c sharp Logo

Access Arrays


A C++ array is a data structure that can be used to store a collection of elements of the same type. Arrays are stored in contiguous memory locations, which means that the elements of an array are stored next to each other in memory.

To declare an array in C++, you use the following syntax:

data_type array_name[size];

 

The data_type specifies the type of the elements of the array, and the size specifies the number of elements in the array.

Example:

int numbers[10]; // Declares an array of 10 integers

 

Once you have declared an array, you can initialize the elements of the array using the assignment operator (=).

Example:

numbers[0] = 1;

numbers[1] = 2;

numbers[2] = 3;

...

numbers[9] = 10;

 

You can also initialize an array using an initializer list. An initializer list is a comma-separated list of values that can be used to initialize an array.

Example:

int numbers[] = {1, 2, 3, 4, 5}; // Initializes an array of 5 integers

 

To access an element of an array, you use the following syntax:

array_name[index]

 

The index is the integer position of the element in the array. The first element of an array has an index of 0.

Example:

int first_element = numbers[0]; // Gets the first element of the numbers array

 

You can also use arrays in loops to iterate over the elements of the array.

Example:

for (int i = 0; i < 10; i++) {

  std::cout << numbers[i] << std::endl;

}

 

This loop will iterate over the elements of the numbers array and print each element to the console.

Multidimensional arrays

C++ also supports multidimensional arrays. A multidimensional array is an array of arrays. To declare a multidimensional array, you use the following syntax:

data_type array_name[size1][size2]...

 

The size1, size2, etc. specify the number of elements in each dimension of the array.

Example:

int matrix[3][3]; // Declares a 3x3 array of integers

 

To access an element of a multidimensional array, you use the following syntax:

array_name[index1][index2]...

 

The index1, index2, etc. specify the integer positions of the element in each dimension of the array.

Example:

int first_element = matrix[0][0]; // Gets the first element of the matrix array

 

Conclusion

C++ arrays are a powerful data structure that can be used to store and manipulate collections of data. Arrays are efficient and easy to use, and they are a fundamental part of the C++ programming language.