Skip to content

Arrays (1)

Course: C++ Part 1 - chapter 8

Collection of elements of similar type is called an array. Similar to javascript. However, as C++ is strictly typed, we can only store elements of a single type, unlike Javascript.

Each array element has some index. It starts from 0. We will learn more about the actual meaning of indices, once we go through pointers.

https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRz2lsNfHvHJg6yXapW_lzZf5SIlSBV8wSPka8BWzvj&s

int arr[] = {1, 2, 3, 4};
// You either need to specify the size or initial elements.
int arr[10];

To create dynamic sized arrays, we can do the following:

int n;
cin>>n;
int arr[n];
// Now take input
for(int i=0; i<n; i++) {
cin>>arr[i];
}

The above arrays created have fixed size (i.e. once created, the size is not changed). If you want to dynamically change array size, you can use pointers to create a dynamic array and change its size using realloc. However, there is a C++ collection called vector that allows us to create dynamic arrays.

Similar to javascript we can run a for loop

int arr[n];
for(int i=0; i<n; i++) {
cin>>arr[i];
}

We can also run for-each loops as well, these assigns the array values to the variable directly instead of needing to access by index.

for(int x: arr) {
cout<<x<<" ";
}

We can access elements of array using their index. For example, arr[3] gives the element at index 3, which is the 4th element of the array (Remember, array indices are 0 based)

We can assign values to array elements using = operator. Example:

arr[0] = 10;
arr[i] = i + 10;