course content

Course Content

C++ Introduction

Introduction to ArraysIntroduction to Arrays

An array is a collection of elements of the same type. To create an array, you should follow these steps:

  • Define the data type for the elements you intend to store in the array;
  • Assign a name to the array;
  • Specify the number of elements in the array by placing this count inside square brackets after its name. 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 within 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.

Note

The index starts at index 0.

The length of the array above is 6. If we create the 5-length array with those numbers, it will throw an error. In this code, I also refer to the 2nd element of the array - 54.

cpp

main.cpp

Suppose there are more elements in the array than you specified when declaring. In that case, a compilation error will occur because the compiler allocates a fixed amount of memory when declaring an array. 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 or have garbage values (unpredictable or arbitrary data).

cpp

main.cpp

You can think of an array as just a book in which each page (element) is numbered (index). 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.
cpp

main.cpp

We have created an array called myArray, which contains four elements, and each element is itself an array with three elements. The process of accessing specific elements within this multidimensional array is illustrated below.

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

Everything was clear?

Section 2. Chapter 5