Зміст курсу
Introduction to C++
Introduction to C++
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:
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:
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:
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];
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];
Дякуємо за ваш відгук!