Showing posts with label Vector. Show all posts
Showing posts with label Vector. Show all posts

Matrix in Functions

In this tutorial from our C++ ebook, we will learn how to work with matrix and functions, learning to declare, invoke and use these two important topics together.

How to Pass a Matrix to a Function

In the study of arrays, we saw that there are some ways to declare the header of functions with arrays as parameters, as follows:
  • type func(tipo *array);
  • type func(tipo array[tamanho]);
  • type func(tipo array[]);

In other words, just pass the pointer (*array - we will study more ahead) or just with the pair of open brackets (array[]).

In the case of two-dimensional arrays, we need to specify the number of columns in the array we are sending:
  • void func(int arr[][COLUMN]);

You see, the number of rows is not mandatory (we can even pass), but the number of columns is.
Let's declare and initialize a 2x2 matrix and then send it to the show() function, which will simply display it as a table, see how our code looks:
#include <iostream>
using namespace std;

void show(int arr[][2], int row)
{
    for (int i=0 ; i<row ; i++){
        for(int j=0 ; j<2 ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[][2]={ {1,2}, {3,4} };
    show(arr, 2);
    return 0;
}
Look some important things in the code above.

First, we pass the array arr[][2] to the function, with the number of columns.
But what about the number of lines? How will the function know how many lines to print the table?
It doesn't know, so we pass another parameter in the function, the integer 'row'.

C++ Matrix: Passing by Reference

All data passing to functions that involve arrays and matrix is by reference. Ever.
That is, passed an array to a function? It will directly access the array and its data, directly into memory. It is not a copy that goes to function, it is not a pass for value, ok?

That means one thing: watch out! Functions can modify the arrays, always remember that.
The code below introduces the 'init' function, which will receive an array and initialize each element of it, asking the user:
#include <iostream>
using namespace std;
const int COLS = 3;
const int ROWS = 3;

void init(int arr[][COLS], int ROWS)
{
    for(int i=0 ; i<ROWS ; i++)
        for(int j=0 ; j<COLS ; j++){
            cout << "matrix["<<i+1<<"]["<<j+1<<"]: ";
            cin  >> arr[i][j];
        }
}

void show(int arr[][COLS], int ROWS)
{
    for (int i=0 ; i<ROWS ; i++){
        for(int j=0 ; j<COLS ; j++)
            cout<<arr[i][j]<<"  ";
        cout<<endl;
    }
}

int main()
{
    int arr[ROWS][COLS];
    init(arr, ROWS);
    show(arr, ROWS);
    return 0;
}
To improve the organization, we have already defined the rows (ROWS) and columns (ROLS) as global variables of the constant type, so that there is no danger of anyone, anywhere in the code, changing their values. This makes the code clearer and safer for maintenance.

Array of arrays in C++

Matrix Exercise in C ++

Create a 4x4 matrix, where each row represents a student's grades, and each column is a different subject. You must create a function that will fill in the students' grades, one by one, indicating which is the subject and which is the student.

Then, your program should display, in an organized manner, the grades of each student, as well as the average of each, the class average for each subject, and the general average, of all students of all grades.

Post your solution in the comments.

Matrix in C++: Array of Arrays

In this tutorial from our C++ Course, we will learn the important concept of matrix in C++.

Array of Arrays - What is it? What is it for?

So far, in our arrays section, we have created arrays of integers, float, doubles, char etc.
That is, we create arrays that store numbers or characters.
However, it is also possible to store other things in arrays.

A curious thing to store in arrays are other arrays.

For example, imagine that you were hired by a school to do a C++ program that will, among other things, store students' grades. Each student has, for example, 5 different grades.

You can, first of all, reason like this: create an array to store students.
For example: students[10]

However, each student has 5 grades. So each student will have an array of grades:
notes[5]

You see: we have an array of students, each block represents a student. And within each block, that is, each student, there is a kind of internal array, with the grades of each student. Each student has his own array of grades, and each student is part of the student array.

Shall we formalize this?

How to declare an Array in C++

We call it a matrix, an array of arrays, or multidimensional arrays.
So far, we only work with arrays of one dimension, just a 'line' of blocks, which form an array.

To increase the number of dimensions of an array, just add pairs of square brackets, for example:

  • To declare an array of one dimension, we do: float grade[5];
  • To declare an array of two dimensions, we do: float students[10][5];


Come on. When we do 'float grade[5]' we mean: 5 float blocks.
When we do: 'float students[10][5]', we mean: 10 blocks, where each block has an array inside, of 5 floats.

We say that this is a 10x5 matrix (10 rows and 5 columns, where each row represents a student, and each column represents a different grade).

To make it easier, let's imagine a 3x3 matrix, we declare it like this:

  • int matrix[3][3];


The expression 'matrix[3]' means: an array of 3 elements.
What does each element contain? An integer? A float? A char? No, each element is another array, of size [3].

See the representation of this matrix:
Matrix in C++

The first element of our matrix is: matrix[0]
It is an array, of 3 elements, which are represented by:
First element: matrix[0][0]
Second element: matrix[0][1]
Third element: matrix[0][2]


The second element of our matrix is: matrix[1]
It is an array, of 3 elements, which are represented by:
First element: matrix[1][0]
Second element: matrix[1][1]
Third element: matrix[1][2]

The third element of our matrix is: matrix[2]
It is an array, of 3 elements, which are represented by:
First element: matrix[2][0]
Second element: matrix[2][1]
Third element: matrix[2][2]

That is, to declare an array of 'i' rows and 'j' columns, we do:

  • type matrix[i][j];


If you have studied matrix and determinants at school, you should remember how to use a matrix, how to flag each element, etc. The only difference here is that the count starts from index 0, instead of 1.

How to initialize a Matrix in C++

We will create a matrix to store the grades of 3 students, where each student has two grades.
That is, we will have a matrix of 3 rows (one for each student) and 2 columns (each column represents a grade). We declare this matrix, then:

  • grade float[3][2];


We will now initialize a 3x3 matrix, for example, with the notes:
float grade[3][3] = {{9.5, 9.1},
                                {8.8, 8.4},
                                {10.0, 10.0}};


The first student's grade array is: {9.5, 9.1}
The second student's grade array is: {8.8, 8.4}
The third student's grade array is: {10.0, 10.0}

For example, what is the second student's first grade? Second student is student 1, first grade is index 0, so that grade is stored in: grade[1][0] = 8.8
The second grade of the second student is: grade[1][1] = 8.4

Simple, isn't it?

Sorting Array Elements in C++

In this tutorial of our C++ course, we will learn how to order the elements of an Array.

Sort elements (sorting)

Sorting, that is, placing elements (such as numbers) in a certain order (such as increasing or decreasing, for example), is one of the most important and studied subjects in computing, due to its importance.

At your school or university, the list of students is sorted alphabetically.
The polling stations where you are going to vote also use some kind of order.
Bank accounts also organize everything according to numbers, as well as the numbers on a lottery card.
When you are a professional C++ programmer, your company will ask you to organize several things, in some kind of order, such as names, salaries, identifications, positions, size or weight of products, etc. etc.

That is, it is an absurdly used subject, too important indeed, that you will use a lot, several times, in your career, and we will introduce now in this tutorial, a little of the subject.

How to sort an Array in C ++

We will use the Selection Sort algorithm to order the elements of the Array.
First, we created the gen() function, which will generate random numbers from 1 to 100.

Let's create an array of size=10 and name 'num'.

We will then fill each position in this array with a random number, and then print this array of random values. Next step now is to order this array,

The logic is as follows: we take the first element of the array, and compare it with all the others. That is, we compare element 0 with index 1, then 0 with index 2 ... until it reaches 0 with index 9.
If these other elements are less than index 0, we invert the values ​​of these two elements. Okay, at the end of this operation, the lowest value of the array will be at position 0.

Now we are going to place the second smallest value at index position 1.
For this, we will compare element 1 with 2, then 3, then 4 ... until we compare element 1 with element 9, the last. Again, if this other element is less than index 1, we invert their position.

At the end of this step, the second lowest value will be in position 1. Now just do this for elements 2, 3, ... 7 and 8. In the last 'round' of comparisons, we compare element 8 with 9 to decide which is bigger and which is smaller.

The first looping, using a for loop, is what controls the first element, and inside it we are going to compare with all the other indexes.
We will use the 'prev' variable to receive the first index. It ranges from 0 to 'size-2' (from 0 to 8, that is: for (prev=0; prev<size -1; prev++)).

The second loop, a nested loop, will compare the 'prev' index with all the other elements in the array.
The second index will be stored in the variable 'next', it always starts with the value 'prev + 1' (when the first element is 0, it starts from 1 ... when the first element is index 1, it starts at index 2, etc etc ... until the first element is index 8 and it will be index 9), until 'size-1' (ie for (next=prev+1; next<size; next++) ) .

Within this inner loop, we use an IF conditional test to find out if the second element is less than the first, if it is, we invert the values ​​of these elements.

See how our code looks:
#include <iostream>
#include <random>
using namespace std;

int gen()
{
    std::random_device rd;
    std::mt19937 gen_numb(rd());
    std::uniform_int_distribution<> dis(1, 100);

    return dis(gen_numb);
}

int main()
{
    int size=10, prev, next, aux;
    int num[size];

    for(aux=0 ; aux<size ; aux++){
        num[aux] = gen();
    }

    cout<<"Original Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    // Selection sort algorithm
    for(prev=0 ; prev<size-1 ; prev++)
        for(next=prev+1 ; next<size ; next++){
            aux=num[prev];

            if(num[next]<num[prev]){
                num[prev]=num[next];
                num[next] = aux;
            }
        }

    cout<<"Ordered Array: "<<endl;
    for(aux=0 ; aux<size ; aux++)
        cout<<num[aux]<<" ";
    cout<<endl;

    return 0;
}

Array Exercises

01. Make an algorithm that orders the elements of an array from major to minor, that is, decreasing order.

02. Place the previous code inside functions: function that fills the array, function that inverts two values, function that makes the selection sort and function that displays arrays. Use function prototypes, to make your code very professional.

Solution in the e-book

How to Find the Highest and Lowest Element in Arrays

In this tutorial, we will do an interesting exercise, which involves arrays and searching. We are going to generate an array of 1 million elements, with random values, and we are going to have the machine scan this giant array, looking for the largest and smallest elements in the array.

Searching in Arrays

First, we define the size of our array, which will be SIZE, which will be a constant of 1 million.
Then, just declare our array, named 'numb': numb[SIZE];

We will declare an auxiliary variable, the 'count', and two others that will store the value of the highest and lowest value contained in that array.

Let's first go in search of the biggest element.
The logic is as follows: at first, let's assume that the first element of the array, the one with index 0, is the largest. So, we do:
highest = numb[0];

What we have to do is go through the entire array, starting from index 1 and compare all other elements with the value stored in 'highest'.

Let's compare if the element 'numb [1]' is greater than 'highest'.
Let's compare if the element 'numb [2]' is greater than 'highest'.
Let's compare if the element 'numb [3]' is greater than 'highest'.
...
Let's compare if the element 'numb [999999]' is greater than 'highest'.

These comparisons we will do with a simple IF conditional test, inside a FOR looping that will go through all the elements of the giant array:
if (numb[count]> highest)

Now, if any element is greater, we must change the value stored in 'highest' to this new value, do you agree? In short, just do:
highest = numb [count];

Our code looks like this:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    const int SIZE = 1000000;
    int numb[SIZE], count, highest, lowest;
    srand( time(0) );

    for (count=0; count<SIZE; count++ )
        numb[count] = rand();

    highest=numb[0];
    for (count=1; count<SIZE; count++){
        if (numb[count] > highest)
            highest = numb[count] ;
    }

    lowest=numb[0];
    for (count=1; count<SIZE; count++){
        if (numb[count] < lowest)
            lowest = numb[count] ;
    }

    cout<<"Biggest : "<<highest<<endl;
    cout<<"Smallest: "<<lowest<<endl;
}
And to find the lowest value?
The logic is the same.

We cause the lowest value to initially store the value of the first element of the array:
lowest = numb[0];

Then we compare all other elements of the array with this 'lowest', checking if the other elements of the array are MINOR, that lowest, if they are, we update the new value of lowest.

In fact, we can even merge these two FOR loops with nested IFs, in one loop, see:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    const int SIZE = 1000000;
    int numb[SIZE], count, highest, lowest;
    srand( time(0) );

    for (count=0; count<SIZE; count++ )
        numb[count] = rand();

    highest=numb[0];
    lowest=numb[0];

    for (count=1; count<SIZE; count++){
        if (numb[count] > highest)
            highest = numb[count];

        if (numb[count] < lowest)
            lowest = numb[count];
    }

    cout<<"Biggest : "<<highest<<endl;
    cout<<"Smallest: "<<lowest<<endl;
}
1 million elements, and we find the smallest and largest elements almost instantly. Powerful this scheme of searching with arrays and loops, don't you think? C++ is awesome.

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;

}