Arrays in C++: What are they? What is it for?

In this introductory tutorial of our Arrays section, we will begin to study this important subject and tool, which you will use a lot, in your C++ programs.

What is an Array?

The array is a type of data structure (data collection), of the same type. That is, it is an existing way of working with various amounts of variables.

So far, we have studied only unique variables, which receive and store a single piece of information, such as a number. It is a memory block reserved to store some data.

In the case of the array, it is a group of variables of the same type. When we declare a array, C++ goes there and reserves a very large block of memory, enough to fit several variables, all addresses are neighbors.

Like structs and classes, arrays are static, that is, during execution they always have the same size.

Initially, we will study arrays in the style of C language, based on pointers (which we will study soon). Later in our course, in the STL (Standard Template Library) section, we will get to know arrays as complete and much more versatile objects.

But first, we need to understand a little more about arrays.

What is an array for ?
An array of one dimension, with 6 elements (variables of the same type)


What is an array for?

Imagine that you want to average two students in your class.
Just declare two variables: a and b, and do (a + b) / 2
Simple, right?

What if you want to average three students grades?
Time, of course: (a + b + c) / 3

Cool ... what if you want to average a class of 30 students?
Will you declare 30 variables and do: (a + b + c + d + e + f + g ....) / 30?

It doesn't even have 30 letters in the alphabet.

That's where the concept of array comes in.
Let's just declare a float array, for example, of size 30.

That is, 30 float variables, memory neighbors, will be allocated on your machine, at once, when creating this array.

Basically, this is what an array is for: let's learn how to declare, initialize, use and handle large blocks of information at once, handling 10, 10, 1,000 or 1 million variables at once, in a very automated and simple, through arrays.

No comments:

Post a Comment