course content

Course Content

Introduction to C++

ArraysArrays

An array is a collection of elements of the same type.

To declare an array, you need the following:

  • Specify the data type of the elements that we are going to store in the array;
  • Give a name to the array;
  • Immediately after the name, in square brackets, indicate how many elements we will store in this array. For example:

The compiler will generate an error if the size is not specified in static arrays.

To initialize an array, you need to specify all its elements in curly braces:

To get the element we need from the array, we can refer to it using indexes. Each element of the array has its index, just like every house in your city has its address.

The index starts at index 0.

Now, if I want to pull out of the array, for example, the number 54, then I will refer to the element at index 2.

cpp

main.cpp

Suppose there are more elements in the array than you specified when declaring. In that case, there will be a compilation error because when declaring an array, the compiler allocates a specific number of bytes for it. It's like trying to pour more water into an already full glass.
If there are fewer elements in the array than you specified when declaring, then all uninitialized elements will be equal to zero.
You can think of an array as just a book in which each page (element) is numbered (index).

cpp

main.cpp

The data in the array can be changed, for this, you need to refer to the element by index and set a new value for it, for example:

cpp

main.cpp

Arrays can be an element of another array, for example, let's declare an array whose elements will be other arrays. To declare a multidimensional array, you need one more pair of square brackets:

  • The first pair of brackets is the main array;
  • The second pair of brackets says that the elements of the main array will be small arrays.

For example:

cpp

main.cpp

We have created an array called myArray, which has four elements and arrays with 3 elements. Array elements are accessed using indexes. The gif below shows how the indexing works in multidimensional arrays.

1. What is an array?
2. What is the index of the third element?
3. Can an array be another array's element?

question-icon

What is an array?

Select the correct answer

question-icon

What is the index of the third element?

Select the correct answer

question-icon

Can an array be another array's element?

Select the correct answer

Section 2.

Chapter 6