Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Basic Concept of the Array | Intro to Arrays
Introduction to C++

book
Basic Concept of the Array

Imagine you have a list of students or a collection of the characteristics of the auto and you want to operate with this data in C++. It will be extremely inconvenient to store the values in single variables. To avoid such problems in C++ you can use arrays. The array is a collection of variables of the same type that stores multiple values.

To declare an array you should specify the type of variables it stores, its name, and the number of elements in square brackets. For example:

python
string students[5];

Here was declared the array students, which consists only of string variables and has 5 elements. To initialize the array print the elements s a list in curly brackets separated by coma:

python
string students[5] = {"Anna", "John", "Emma", "Ross", "Barney"};

The number of initialized values can be less than the number of array elements.

If you don’t know how many elements will have your array, just skip this parameter:

python
int numbers[] = {42, 12, 56, 98};

Each element has its position, the number of its place in the array, it is called index. The very first element has an index 0, the second has an index of 1, and so on:

For example, let's get information about our array of students. You can get access to the array’s element by array’s name and the element's index in square brackets:

string students[5] = {"Anna", "John", "Emma", "Ross", "Barney"};
cout << students[3];
12
string students[5] = {"Anna", "John", "Emma", "Ross", "Barney"}; cout << students[3];
copy

You can also reassign the elements of an array by its index:

string students[4] = {"Anna", "John", "Emma", "Ross"};
students[3] = "Julia";
cout << students[3];
123
string students[4] = {"Anna", "John", "Emma", "Ross"}; students[3] = "Julia"; cout << students[3];
copy
question-icon

Initialize the array numbers of 10 elements type of int, reassign the second element and print it. Remember that the second element will have an index of one less.

#include
using namespace std;

int main() {
    
_ _ _
_ _ _
_ _ _
= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    numbers
_ _ _
= 5;
    cout << numbers
_ _ _
;

    return 0;
}

Click or drag`n`drop items and fill in the blanks

dots
int
dots
[2]
dots
[9]
dots
[1]
dots
[10]
dots
[1]
dots
[2]
dots
double
dots
numbers

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 5. Capitolo 1
some-alt