Introduction to Arrays
Arrays are one of the fundamental data structures in C++. They allow us to store multiple elements of the same type in a contiguous block of memory. Arrays are often used to represent collections of similar objects.
Arrays can be declared and initialized as follows:
TEXT/X-C++SRC
1int myArray[5];
2
3myArray[0] = 10;
4myArray[1] = 20;
5myArray[2] = 30;
6myArray[3] = 40;
7myArray[4] = 50;
In the above code snippet, we declare an integer array myArray
of size 5. We then assign values to each element of the array using the subscript operator []
.
To access an element of an array, we can use the subscript operator []
followed by the index of the element. For example, to access the element at index 3, we would use myArray[3]
. The output of the above code would be:
SNIPPET
1Element at index 3: 40
xxxxxxxxxx
19
using namespace std;
int main() {
// Array declaration
int myArray[5];
// Array initialization
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;
// Array access
cout << "Element at index 3: " << myArray[3] << endl;
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment