-
-
Notifications
You must be signed in to change notification settings - Fork 1
Arrays
C++ arrays are data structures that allow us to store a collection of elements. They are linear data structures which can be used to store elements of the same data type in a contiguous block of memory.
To declare an array in C++, we use the following syntax:
data_type array_name[array_size];
where data_type
is the type of data the array stores, array_name
is the name of the array, and array_size
is the size of the array.
For example, to declare an array of 10 integers, we would use the following syntax:
int myArray[10];
Once an array is declared, we can initialize its elements. To do this, we use the following syntax:
data_type array_name[array_size] = {val1, val2, val3, ...};
where val1
, val2
, etc. are the values that we want to assign to the array elements.
For example, to initialize an array of 10 integers to all zeros, we would use the following syntax:
int myArray[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Once an array is declared and initialized, we can access any of its elements using the following syntax:
array_name[index];
where index
is the index of the element we want to access.
For example, to access the fourth element of the array myArray
, we would use the following syntax:
myArray[3];
To iterate through all the elements in an array, we can use a for
loop. The syntax for this is as follows:
for (int i = 0; i < array_size; i++)
{
// Access array elements here
array_name[i];
}
where i
is the loop iterator, array_size
is the size of the array, and array_name
is the name of the array.
For example, to iterate through all the elements of the array myArray
, we would use the following syntax:
for (int i = 0; i < 10; i++)
{
// Access array elements here
myArray[i];
}
C++ arrays are an important data structure that allows us to store a collection of elements of the same data type. We can declare, initialize, access, and iterate through the elements of an array using the syntax provided in this article.