In C++, an array is a collection of elements of the same data type that are stored in contiguous memory locations. To create an array in C++, you need to specify the data type of the elements and the number of elements in the array.
There are two ways to create an array in C++:
- Declare and initialize the array at the same time:
int myArray[5] = { 1, 2, 3, 4, 5 };
In this example, an integer array named myArray
is created with 5 elements and initialized with the values 1, 2, 3, 4, and 5.
- Declare the array and initialize the elements one by one:
int myArray[5];
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;
In this example, an integer array named myArray
is declared with 5 elements and then each element is initialized one by one.
To access the elements of an array, you can use the index operator []
. For example:
int x = myArray[2]; // access the third element of myArray
Note that in C++, array indices start at 0, so the first element of an array is at index 0, the second element is at index 1, and so on.
Comments
Post a Comment