 Save up to 80 % on our C and C++ e-learning courses. Only this week!

# Lesson 8 - Arrays in the C++ language

In the previous exercise, Solved tasks for C++ lessons 6-7, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on arrays in C++ instead of a thorough-full lesson? Here it is:

Shortened initialization of an array:

`int numbers[] = {2, 3, 5, 7};`

Writing `1` at the position ``:

`numbers = 1;`

Reading the value (now `1`) at the position ``:

``````{CPP_CONSOLE}

int numbers[] = {2, 3, 5, 7};
numbers = 1;

cout << numbers << endl;
{/CPP_CONSOLE}``````

Printing the whole array:

``````{CPP_CONSOLE}

const int numbersCount = 4;
int numbers[] = {2, 3, 5, 7};
numbers = 1;

for (int i = 0; i < numbersCount; i++)
cout << numbers[i] << " ";
{/CPP_CONSOLE}``````

Creating an empty array and generating the values using a `for` loop:

``````{CPP_CONSOLE}
const int numbersCount = 16;
int numbers;
for (int i = 0; i < numbersCount; i++)
numbers[i] = i + 1;

for (int i = 0; i < numbersCount; i++)
cout << numbers[i] << " ";
cin.get();

{/CPP_CONSOLE}``````

Sorting using `sort()`:

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 2, 1, 4, 5, 3 };
sort(numbers, numbers + numbersCount);
// print the array
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << " ";
}
cin.get();

}
``````

Searching for an element in an array using `find()`:

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = {2, 3, 3, 5, 7};
int *i = find(numbers, numbers + numbersCount, 3); // find number 3
int position = i - numbers;
if (position < numbersCount)
cout << "Element 3 found at the position " << position << endl;
else

}
``````

Calling more C++ array functions:

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = {2, 3, 3, 5, 7};
int *min = min_element(numbers, numbers + numbersCount);
int minPosition = min - numbers;
cout << "min_element: " << *min << " at the position " << minPosition << endl;
int *max = max_element(numbers, numbers + numbersCount);
cout << "max_element: " << *max << endl;
int numbers2[numbersCount];
copy(numbers, numbers + numbersCount, numbers2);
cout << "index 2 in the copy: " << numbers << endl;
cout << "count 3s: " << count(numbers, numbers + numbersCount, 3) << endl;
reverse(numbers, numbers + numbersCount);
cout << "index 2 in the reversed array: " << numbers << endl;
random_shuffle(numbers, numbers + numbersCount);
cout << "index 2 in the shuffled array: " << numbers << endl;
fill(numbers, numbers + numbersCount, 5);
cout << "index 2 in the array filled with 5s: " << numbers << endl;

}
``````

Would you like to learn more? A complete lesson on this topic follows.

In the previous tutorial, Solved tasks for C++ lessons 6-7, we introduced loops in the C++ language. In today's lesson, we're going to introduce you all to the array data structure and show you what it's capable of accomplishing.

## Array

Imagine that you want to store some information about multiple items, e.g. you want to store `10` numbers into memory, each of the fields of a checkerboard or the names of 50 users. Perhaps you get that there must be an easier way than to start typing variables individually like `user1`, `user2` ... up until `user50`. Despite the fact that there may be `1000` of them. How would we go about searching for something in there? Definitely not like that! If we need to store a larger amount of variables of the same type, we do so using an array. We can imagine it as a row of boxes, each of them containing one item. The boxes are numbered by indexes, the first one has an index of `0`. (We see an array of 8 numbers on this picture)

Programming languages are very different in the way they work with arrays. In some, usually compiled languages (C++), we have to specify a fixed size for the array and we are unable to change it during run-time. Meaning that it is not possible to add more "boxes" to an existing array, so we have to keep this in mind at all times. The C++ language also allows us to declare dynamically allocated arrays or use things like linked lists to work around this limitation. However, this requires rather complex knowledge and therefore we'll get to it later. On the other hand, some interpreted languages allow us to declare an array of any size and to change this size during run-time. An example of such a language is PHP.

Maybe you're wondering why we are even bothering learning about arrays if there are obviously many limitations to them and there are better data structures? The answer is: arrays are simple. I don't mean simple for us now (which they are too) but simple for the computer to work with. Since array items are stored in a row in memory and they each occupy the same amount of space, they can be accessed quickly. They're a key data structure. We use loops for mass manipulating array items.

We declare an array using square brackets and specify its length within them. Don't forget to specify the data type before the variable name. In this example, the data type is whole numbers:

`int numbers;`

`numbers` is obviously the name of our variable here.

The size of an array is fixed and specified in the source code. You can try to use a variable instead to specify the value. Visual Studio will mark it as an error.

If we're fine with the fact the length of our array is fixed but we want to specify its size using a variable (e.g. to use it later in a loop's condition), we'd have to use a constant. A constant is a variable whose value can't be modified. We declare it in the same way as an ordinary variable, but we add the `const` keyword before the data type:

```const int numbersCount = 24;
int numbers[numbersCount];```

This doesn't help with modifying the length during the run-time. However, if we as programmers decide to change the length to another fixed number of elements, the constant will change at all places of the program. Without constants, if we used loops to print an array, we could forget to change the new size at one specific point and read outside the array bounds or failed to write all of its items.

We often need to specify the array size using an ordinary variable. Such an array has to be declared dynamically which we'll learn to do in the following C++ course. It's definitely not a good idea to derive into these matters in the basics course.

We access array items using square brackets. Let's store the number `1` at the first index (which is the index `0`).

```const int numbersCount = 24;
int numbers[numbersCount];
numbers = 1;```

Filling the whole array manually like this would be too laborious. Therefore, we'll use a loop and fill the array with numbers from `1` to `10`. We'll use the `for` loop to do just that:

```const int numbersCount = 10;
int numbers[numbersCount];
for (int i = 0; i < numbersCount; i++)
numbers[i] = i + 1;```

Notice that we've got the array length stored as a constant again.

Note: Never, ever try to access items beyond the end of an array (e.g. to access the 20th element of an array which is `10` elements long). If you're lucky, you'll get an undefined result (values which were stored in the memory at that exact moment). If you weren't so lucky, the application will terminate with an error.

To print our array to the console, we'll add the following code below what we currently have:

``````{CPP_CONSOLE}

const int numbersCount = 10;
int numbers[numbersCount];
for (int i = 0; i < numbersCount; i++)
numbers[i] = i + 1;

for (int i = 0; i < numbersCount; i++)
cout << numbers[i] << ' ';
cin.get();
{/CPP_CONSOLE}``````

There is one more way to fill an array with values. If we know all the values right from the start, we can use the following syntax:

`int numbers = {1, 2, 3, 4, 5};`

The array length in brackets can be omitted, it'll be determined automatically according to the number of items. We can also make the array longer than the number of elements we provide in the curly brackets. However, such an array won't have all of the elements initialized.

## Array functions

You'll find many useful functions for working with arrays in the `algorithm` file. We'll introduce you all to some of the. Don't forget to place `#include <algorithm>` at the beginning of your source file!

### `find()`

The `find()` function returns a so-called pointer to the first occurrence of a given value. Since we haven't covered pointers yet, we'll have to settle for knowing that we use asterisks to declare them. If we subtract this pointer to the value from the array itself, we get the position of the value. If the function didn't find the value, the computed position will contain the length of the array. Let's demonstrate it on an example and find the value `7` in an array of several numbers:

``````#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{
const int numbersCount = 5;
int numbers[numbersCount] = { 1, 7, 3, 4, 10 };
int element = 7;
int *i = find(numbers, numbers + numbersCount, element);
int position = i - numbers;
if (position < numbersCount)
cout << "Element found at position: " << position << "." << endl;
else
cin.get();
return 0;
}``````

### `count()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 6;
int numbers[numbersCount] = { 1, 6, 9, 2, 6, 3 };
int c = count(numbers, numbers + numbersCount, 6);
cout << c; // c = 2
cin.get();

}
``````

The `count()` function returns the number of occurrences of a given value in an array - of the value `6` in the example above.

### `copy()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 1, 2, 3, 4, 5 };
int numbers2[numbersCount] = { 0, 0, 0, 0, 0 };
copy(numbers, numbers + numbersCount, numbers2);
// numbers = { 1, 2, 3, 4, 5 }, numbers2 = { 1, 2, 3, 4, 5 }
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << "->" << numbers2[i] << " ";
}
cin.get();

}
``````

The `copy()` function copies contents from one array to another.

Note: The second array has to be the same size as the source array or longer.

### `max_element()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 2, 1, 4, 5, 3 };
int *i = max_element(numbers, numbers + numbersCount);
cout << *i; // i = numbers + 3, *i = 5
cin.get();

}
``````

The `max_element()` function returns a pointer to the highest value in an array. It compares values using the `<` operator. If there are multiple occurrences of the highest value in the array, the pointer will be set to the first one. We can get the position of the value using the same technique we used with `find()`.

### `min_element()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 2, 1, 4, 5, 3 };
int *i = min_element(numbers, numbers + numbersCount);
cout << *i; // i = numbers + 1, *i = 1
cin.get();

}
``````

The `min_element()` function is the exact same function as the one mentioned above, but it returns a pointer to the lowest value in an array. We can retrieve its position as we did in the `find()` function example.

### `sort()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 2, 1, 4, 5, 3 };
sort(numbers, numbers + numbersCount);
// numbers = { 1, 2, 3, 4, 5 }
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << " ";
}
cin.get();

}
``````

`Sort()` sorts the array elements in ascending order (using the `<` operator).

### `fill()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
int numbers[numbersCount] = { 1, 2, 3, 4, 5 };
fill(numbers, numbers + numbersCount, 5);
// numbers = { 5, 5, 5, 5, 5 }
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << " ";
}
cin.get();

}
``````

The `fill()` function fills an array with a given value.

### `reverse()`

``````
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{

const int numbersCount = 5;
// numbers[numbersCount] = { 1, 2, 3, 4, 5 };
reverse(numbers, numbers + numbersCount);
// numbers = { 5, 4, 3, 2, 1 }
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << " ";
}
cin.get();

}
``````

The `reverse()` function "reverses" the array contents, i.e. all of its values will be ordered backwards from what they currently are.

### `random_shuffle()`

``````#include <iostream>
#include <algorithm>
#include <ctime>
using namespace std;

int main(void)
{
srand(unsigned(time(0))); // initializes the random number generator
const int numbersCount = 5;
int numbers[numbersCount] = { 1, 2, 3, 4, 5 };
random_shuffle(numbers, numbers + numbersCount);
// e.g. numbers = { 3, 1, 5, 2, 4 }
for (int i = 0; i < numbersCount; i++)
{
cout << numbers[i] << " ";
}
// Please, notice that if you're using our online compiler
// the result may stay the same for several days because it's cached
// However, you may modify a comment in the source code to force the compiler
// to compile the code again.
cin.get();
}``````

The `random_shuffle()` function shuffles array items randomly. Notice that we have to initialize the random number generator first and we need the `time()` function from the `ctime` library to do so.

That's enough for today, feel free to play around with arrays for a while. In the next lesson, Solved tasks for C++ lessons 8, we'll learn how to work with text in the C++ programming language In the following exercise, Solved tasks for C++ lessons 8, we're gonna practice our knowledge from previous lessons.

Article has been written for you by David Capka The author learned IT at the Unicorn University - a prestigious college providing education on IT and economics.