Arrays in C++: How to Declare, Initialize, Access and Use

Now that we have learned what arrays are, what they are for and where they are used, we will learn to work with them, declaring, accessing and using them in the most varied ways.

How to declare an Array in C++

Just like the variables we've used so far, in our website, to declare a vector, you first need to declare its data type (char, int, double, float, etc.). Then you need to name it too.

Now comes the different part, in array: you need to say the size of your array, that is, how many unique variables that array will contain, and this is reported in square brackets [].

Let's declare some variables.


  • int ID [10]: array with 10 integers to store ID numbers
  • float grades[5]: array with 5 numbers floats, to store grades
  • char name[100]: array with spaces for 100 characters, to store a name or text (also called strings, which we will study in the future)


That's it: type, array name and how many elements it should have.

How to initialize an Array

When declaring, you can already initialize the elements of the array. To do this, we enclose the values in square brackets {}.

For example, an array of 2 integer elements of values 21 and 12:

  • int rush [2] = {21, 12};

If you want to initialize an array of a thousand elements, all with a value of 0, just do:

  • int num [1000] = {};

C++ will automatically fill in all variables with a zero initial value.

You don't even have to declare the number of elements if you are going to initialize directly, C ++ will count how many elements you entered and declare the array with the exact size of what you are using, just leave the square brackets empty.

For example, initializing a string (character array) with the name of our course and displaying a welcome message:
#include <iostream>
using namespace std;

int main()
{
    char site[] = {"Progressive C++"};

    cout << "Welcome to "<< site <<endl;
}

Accessing the Elements of an Array

Suppose we have an array of 3 integers:
int num [3];

The first variable is: num[0]
The second variable is: num[1]
The third variable is: num[2]

Note one essential thing: the first element ALWAYS has an index of 0
The first is a [0] and not a [1].

You can declare a vector of 10, 100, thousand, million ... the first element is accessed using the index 0:
First element: num[0]
Second element: num[1]
...
n-th element: num[n-1]

That is, if your array has size X, you access the elements from index 0, up to index (X-1), ok?

How to use Arrays in C ++

Let's get your hands dirty and see how to use arrays in C++? Ok?

As we will deal with a large number of variables, practically whenever we use arrays, we also use loops to access the arrays more quickly and in a more dynamic and flexible way. Let's see in practice.

Example 1

Place the numbers 0, 1, 2, 3, ..., 9 in an array of 10 elements.
#include <iostream>
using namespace std;

int main()
{
    int num[10], cont;

    for(cont=0 ; cont<10 ; cont++)
        num[cont] = cont;
}

Our auxiliary variable is 'cont', and it receives values from 0 to 9.
The index variable 0 is set to 0.
Index variable 1 is assigned a value of 1.
...
The index variable 9 is given the value 9.

This is done with the command line: num [cont] = cont;

Example 2

Place the numbers 1, 2, 3, ..., 10 in an array of 10 elements, then display them in the format 'Element 1', 'Element 2', ..., 'Element 10'.
#include <iostream>
using namespace std;

int main()
{
    int num[10], cont;

    for(cont=0 ; cont<10 ; cont++)
        num[cont] = cont+1;

    for(cont=0 ; cont<10 ; cont++)
        cout << "Element " << cont+1 << ": " << num[cont] << endl;
}

Now we did it with a difference detail:
The index variable 0 receives the value 1.
Index variable 1 is assigned a value of 2.
...
The index variable 9 receives the value 10.

This is done with the command line: num [cont] = cont + 1;

You see, we programmers, we count from 0. But normal people (?????!) Count from 1. So we have to display 'element 1' as the first, and not element 0. For this, we add 1 to the cont variable,

Example 3

Create a program that asks for the grade of 5 students, store those grades in an array, then display them, as well as your average.
#include <iostream>
using namespace std;

int main()
{
    float grade[5], sum=0;
    int cont;

    for(cont=0 ; cont<5 ; cont++){
        cout<<"Insert the grade "<<cont+1<<": ";
        cin >> grade[cont];
        sum += grade[cont];
    }

    for(cont=0 ; cont<5 ; cont++)
        cout<<"Grade "<<cont+1<<": "<<grade[cont]<<endl;

    sum /= 5;

    cout<<"Average: "<<sum<<endl;

}
We will store the notes in the 'grade' array, and the sum of the notes in the 'sum' variable. Our accountant is the 'cont'.

First, we use a FOR loop to ask the user for the 5 grades.
Each time he types a note, it is assigned to an element of the array, then the sum variable (which must initialize to 0) is added.

Then, we display all the typed notes.
Finally, just divide the variable 'sum' by 5 and we will have the average of the typed grades.

Note that the code size would be the same for 1 million notes, it would be enough to change the number 5 to 1000000. See how the arrays make our possibilities to create programs much more flexible?

Example 4

Create an array of 101 elements. In each element of the array, store the value of double of the index. That is, the variable num[x] must have stored the value 2x. Then, it displays the list of the 100 first even numbers.
#include <iostream>
using namespace std;

int main()
{
    const int ARRAY_SIZE = 101;
    int num[ARRAY_SIZE], cont;

    for(cont=0 ; cont<ARRAY_SIZE ; cont++)
        num[cont] = 2*cont;

    for(cont=1 ; cont<ARRAY_SIZE ; cont++)
        cout<<"Double of "<<cont<<": "<<num[cont]<<endl;

}
Arrays must always be initialized with a literal value (a number directly) or with a variable, preferably constant (const). In fact, it is recommended that you declare a constant at the beginning of the program and keep using variables during the code, it is easier for future changes.

Example 5

Ask 6 employees of a company to enter their salaries. Then, your program should tell you how much income tax each of them must pay per month. The fee is 15%.
#include <iostream>
using namespace std;

int main()
{
    const int ARRAY_SIZE = 6;
    float func[ARRAY_SIZE];
    int cont;

    for(cont=0 ; cont<ARRAY_SIZE ; cont++){
        cout<<"Employee "<<cont+1<<": ";
        cin >> func[cont];
    }

    cout<<"Fee to pay: "<<endl;
    for(cont=0 ; cont<ARRAY_SIZE ; cont++)
        cout<<"Employee "<<cont+1<<": R$"<<func[cont]*0.15<<endl;

}

No comments:

Post a Comment