I'm studying algorithms with Portugol and I'm having difficulty understanding the vector's function in code. I already know how to use this structure.
I'm studying algorithms with Portugol and I'm having difficulty understanding the vector's function in code. I already know how to use this structure.
A vector is usually a variable that can contain multiple values (can be just an object not stored in variable).
You use it when you need to store a sequence of values in memory. In general these values represent the same thing and it is very common to be of the same type. Some languages even require it to be of the same type, ie all are integers, or all are of the character type.
Technically each of the vector elements ends up being a variable as well. So we can say that a vector is a collection of variables .
A vector is a specialized form of matrix that we all learn in mathematics. We can say that a vector is a single row or a single column of an array.
Each of the elements or items, as they are called, are accessed through an index, usually numeric indicating their position in the sequence. It can be accessed by a literal (a number) or by another variable that indicates the position number, or an expression that calculates that number.
When we declare a vector we are reserving a space in memory for how many elements it will contain. Then a vector of 10 elements of an integer type usually allocates roughly 40 bytes (10 x 4 bytes of integer size).
Exact functioning can vary from language to language. Some are more flexible. Some may experience loss of performance. In Portugol this is not important.
Depending on the language, there may be a more specific definition. Some differentiate the array , array , list , etc. Others use these terms interchangeably or use more specific terms for some variation of the vector. Portugol uses the simplest definition, for those who are learning it is not interesting to understand all the nuances.
Think you have 50 student grades, you could do this:
leia(nota1)
leia(nota2)
leia(nota3)
.
.
.
leia(nota50)
Complicated to do this, right? It could simplify, automate repetition. How to access each one? How to generalize all this? Using the vector:
leia(nota[1])
leia(nota[2])
leia(nota[3])
.
.
.
leia(nota[50])
Now it has a vector, a simple change, but the code is still bad:
para i de 1 ate 50 faca
leia(nota[i])
fimpara
In this way 50 lines have turned into 3. It does the same thing automated. Use math and flow control to get the same result.