Array Definition
Understanding what arrays are and how to use them
Arrays
Today we will get acquainted with arrays, also called Array in English, and learn to work with large amounts of data.
Array Definition
An array is a data structure that allows you to store elements of the same type in a sequence. They are an important part of programming and allow us to efficiently work with large amounts of data.
In simple words, an array is a way to store multiple variables at once. If previously we used only one, two, or three variables a, b, c, now we will learn to have one array that will store all values. You can think of an array as a horizontal box with many cells.
And in each cell, we have variables of a specific type.
Array Declaration
Here's how to declare an array:
In an array, we have two main components:
- Data type: determines the type of elements that will be stored in the array.
- Size: specifies the number of elements that can be stored in the array.
Working with Arrays
Let's look at an example of an array that stores five integer values:
In this example, we declare an array numbers that can store five integer values. Each element of the array has its own index, starting from 0.
Assigning Values to Array Elements
We can assign values to array elements as follows:
In this example, we assign values to elements of the numbers array with indices from 0 to 4.
Important: Array indices start from 0, not 1. So if we have an array of 5 elements, the indices will be: 0, 1, 2, 3, 4.
Getting Values of Array Elements
We can also get values of array elements using their indices:
In this example, we output the values of elements of the numbers array using cout. Notice that we use indices from 0 to 4 to access each element.
Execution Result
The result will be as follows:
Using Loops with Arrays
Arrays also allow us to use loops to traverse and perform operations on array elements.
For example, here's how we can use a for loop to output all elements of an array:
In this example, we loop through the numbers in our array and use i to access array indices.
Complete Program with Array
Array Initialization During Declaration
You can also initialize an array immediately upon declaration: