Arrays
To also create a motivation for learning the structure we will present, we will start with a problem statement:
A number n is requested from the keyboard, then n natural numbers. We consider 1 ≤ n ≤ 1000 and the values of
maximum 9 digits. We have two requirements:
a) Determine the largest value among the n;
b) Determine how many of the read values are equal to the last one entered;
For exercise a) the solution is known (and recommended) using a few simple variables, right in
data reading time:
#include <iostream<
using namespace std;
int n, maxim, x, i;
int main () {
cin>>n;
maxim = -1;
for (i=1;i<=n;i++) {
cin>>x;
if (x > maxim)
maxim = x;
}
cout << maxim;
}
Here we notice that all the numbers have been read (and stored) in the same variable and immediately after reading I have used value comparing it to the maximum.
To solve the second requirement we note that when reading the last value it is necessary to we know the value of the others, read before. So we need, in this case, to have memorized at the end all numbers entered. With the way of using variables used so far we could not solve. It questions like: how do I declare up to 1000 variables? What do I call them? And so on
Programming languages provide solutions to such problems by using memory arrays
A memory array consists of several variables, all of the same type, that can be accessed using the name of the array and a number (or, as we will see later, several numbers) representing the position in the array.
Example:
Name | Description | |
---|---|---|
int x; | One int variable. | |
int v [ 100 ]; | 100 int variables. | |
From the example we deduce the general way to declare arrays:
type name [ size ];
- type represents the common type of all array elements; any type of language can be used;
- name represents the identifier with which we refer to the compound variable v;
- size must be a constant expression (that is, it can contain constants and possibly with operations they); this value represents the number of elements (type variables) of the array;
The components of the array are accessed in the program by constructions of the form name [ position ], where position represents an expression of type integer, not necessarily constant, and whose value, at the time of access, must be between 0 and dimension-1.
So the positions (indexes) of the elements of an array are numbers with values between 0 and size-1.
The components of an array are regular variables of common type and can be used anywhere o is allowed variable of that type.
Let:
int v [ 100 ]; int i, x; |
Description: |
|
---|---|---|
cin >> v [ 3 ]; | Right, what asks the keyboard for a value and stores it in the fourth array component (numbering starts from 0). | |
v [ 2 ] = 2 * v [ 3 ]; | It is a correct assignment involving two components of the array. The on the left is the variable whose value will change. | |
i = 2;
cin >> x; v [ i ] += 10 * x; |
Three variables of type int intervene here. We note that we can have a
component of the array to the left of an assignment (something can be stored in it as in any other variable of type int). |
|
To better understand what a vector represents, we can think of an int v [ 2 ] declaration as same as if we had declared int a , b;
Now it's time to see how we actually use a vector in a program. More specifically, we will solve it point b) of the stated problem.
We will follow this steps:
- we declare a vector that can store at least 1000 elements of type int;
- we read n and the n numbers from the keyboard and, very importantly, store them in the vector;
- we loop through the vector again to compare its elements with the last read, thus finding the result.
#include <iostream>
using namespace std;
int n, i, cnt;
int v[1001];
int main () {
cin >> n;
for (i = 1; i <= n;i++) {
cin >> v[i];
}
cnt = 0;
for (i = 1; i<= n;i++)
if (v[n] == v[i])
cnt++;
cout << cnt;
}
Remarks:
- the appropriate structure to traverse the vector element by element is for;
- we decided to use the components in positions 1, 2, ..., n; thus the component on position 0 remains unused; the components on positions n+1, n+2 also remain unused ... 1000 (I declared the array with size 1001, so its available components are on positions 0, 1, ..., 1000).
- The fact that we use components from positions 1..n (and not 0..n-1) is to get used to faster novice programmers using arrays.
- We have for an array a physical dimension (1001, the declared one) and a logical one (n – the number of actually used components);
Let's analyze the program above. The first repeating structure causes the index i to take values of each in turn positions in v where there are elements where we want to store the entered values. The sequence is equivalent to:
cin >> v [ 1 ]; cin >> v [ 2 ]; cin >> v [ 3 ]; … cin >> v [ n ]; (and we without using a repetition don't we can achieve this effect of dots dots).
After finishing this repetition, the numbers we entered are all in memory, one by one
component of the array, so we can use them for other purposes.
We now again traverse the elements of the array, testing by comparison which are equal in value to the stored one
on the last position.
We can conclude: in general, the elements of a vector, located between positions p1 and p2 (with p1 ≤ p2) can
visit with a sequence of the form:
for (index = p1; index <= p2; index++)
access the item v [ index ];
Solved Problems:
1. The keyboard asks for n number (maximum 4 digits) and then n integers with maximum 9 digits. Find:
a) Storing the numbers read in a vector in positions from 1 to n;
b) Sum of even values (if there are no even values, 0 will be displayed);
c) The sum of the values on the even positions;
d) The number of nule values;
e) The maximum of negative elements (if there are no negative values, 0 will be displayed);
f) The average of two-digit values (if there are no such values, 0 will be displayed);
Solution:
The problem is a good exercise for applying some basic operations to a string of numbers that has items stored in memory. Each requirement can be solved without the need to use a single vector, but we will now do it after memorizing the elements, being, on the one hand, a didactic application, on the other hand other requirements may be part of a larger application that requires memorizing elements.
All requirements require the classical traversal of a one-dimensional array, for example with a for. I chose option to solve each requirement individually with a separate repetitive structure, but we know that one could use a single repetition for all (right at the time of reading, especially since I noticed that there was no need for the stored elements).
#include <iostream>
using namespace std;
int n, i, sumaPare, sumaPozitiiPare, z;
int maxim, s, nr;
int v[10001];
/**
I declared the vector to fit
the maximum possible number of components
according to the statement
**/
int main () {
cin >> n;
/// reading the number of inputs
for (i = 1; i <= n; i++) {
cin >> v[i];
}
/// the sum of even values
sumaPare = 0;
for (i = 1; i <= n; i++)
if (v[i] % 2 == 0)
sumaPare += v[i];
cout << sumaPare << "\n";
/// the sum of the values on even positions
sumaPozitiiPare = 0;
for (i = 2; i <= n; i += 2)
sumaPozitiiPare += v[i];
cout << sumaPozitiiPare << "\n";
/** or
for (i = 1; i <= n; i++)
if (v[i] % 2 == 0)
sumaPozitiiPare += v[i];
**/
/// numarul valorilor nule
z = 0;
for (i = 1; i <= n; i++)
if (v[i] == 0)
z++;
cout << z << "\n";
///maximul elementelor negative
maxim = -1000000000;
for (i = 1; i <= n; i++)
if (v[i] < 0 && v[i] > maxim)
maxim = v[i];
if (maxim == -1000000000)
cout << 0 << "\n";
else
cout << maxim << "\n";
///media aritmetica a valorilor de doua cifre
s = 0;
nr = 0;
for( i = 1; i <= n; i++)
if (v[i] > 9 && v[i] < 100) {
s += v[i];
nr ++;
}
if (nr == 0)
cout << 0;
else
cout << s*1.0/nr;
}
2. The elements of a vector known to be distinct are read. Show the ones in between maximum value and minimum value
Solution:
#include <iostream>
using namespace std;
int v[1001];
int n, i, maxim, minim, pmaxim, pminim, aux;
int main() {
cin >> n;
for(int i = 1; i <= n; i++){
cin >> v[i];
}
minim = v[1];
maxim = v[1];
pminim = 1;
pmaxim = 1;
for(int i = 2; i <= n; i++){
if(v[i] < minim){
minim = v[i];
pminim = i;
}
if(v[i] > maxim) {
maxim = v[i];
pmaxim = i;
}
}
if(pmaxim &st; < pminim) {
aux = pmaxim;
pmaxim = pminim;
pminim = aux;
}
for(int i = pminim; i <= pmaxim; i++)
cout << v[i] << ' ';
return 0;
}