Course Introduction to Programming
Arrays
In this lesson, we will learn the fundamental concepts about Vectors, one of the most important data structures in programming.
You will understand what vectors are, what they are for, how they work in the C language, how to access and manipulate their elements, and you will see practical examples to apply these concepts in your own code.
What is a vector?
A vector is a data structure that stores a collection of elements of the same type in consecutive memory locations. Thus, vectors are homogeneous, that is, the variables stored by a vector are all of the same type.
In other words, it is like a "box" with several numbered compartments, where each compartment holds a value. Each value can be accessed through its position (index).
What is a vector for?
Vectors are used to store and organize a known quantity of data of the same type. Thus, instead of declaring numerous individual variables, we use a single vector with a defined size.
We can also use vectors to automate tasks, since by using repetition structures, we can apply the same logic or calculation to all elements of the vector with a single block of code.
Vectors in C
The declaration of a vector in C follows the template below:
<type> <name>[<size>];
To make it easier to understand, analyze the example below:
/*
type -> int (stores integers)
name -> vector
size -> 3 (stores three elements)
*/
int vector[3];
When declaring a vector, the computer will reserve a set of sequential memory locations. This means that, in the example above, the computer has reserved three sequential positions capable of storing integers.
Observations:
- Vectors in C have the same size from their declaration until the end of the program.
- We can use the
sizeofcommand to find out the number of bytes in a vector. If we want to know how many elements it actually has, we just need to divide the size in bytes of the vector by the size in bytes of the vector's type:
#include <stdio.h>
int main(){
int v[5];
printf("Size in bytes of an integer -> %d\n", sizeof(int));
printf("Size in bytes of vector v -> %d\n", sizeof(v));
printf("Number of elements in vector v -> %d\n", sizeof(v)/sizeof(int));
}
/* Output:
Size in bytes of an integer -> 4
Size in bytes of vector v -> 20
Number of elements in vector v -> 5
*/
How to access the elements of a vector?
The name of the vector is treated as a pointer to the first memory location reserved for it. Thus, to access each position of the vector, we can use both pointer arithmetic and the [ ] operator, indicating in square brackets which position we want to access.
As an example, let's analyze the access to the elements of the vector int x[4]:
| *x | *(x+1) | *(x+2) | *(x+3) |
|---|---|---|---|
| x[0] | x[1] | x[2] | x[3] |
Notice that, when using the [ ] operator, the first position of the vector is given by the index
Observation: pointer arithmetic works because the set of positions reserved for the vector is sequential. To make it easier, see the output of the code below:
#include <stdio.h>
int main(){
int v[3];
/*
Since the size of an integer is 4 bytes, the distance between
two consecutive positions of vector v must also be 4 bytes
*/
printf("First position -> %d\n", &v[0]);
printf("Second position -> %d\n", &v[1]);
printf("Third position -> %d\n", &v[2]);
}
/* Output:
First position -> 6422292
Second position -> 6422296
Third position -> 6422300
*/
How to assign values to the elements of a vector?
There are two ways to assign values to the elements of a vector:
1. Changing all elements of the vector
This is the only method that can be used along with the declaration.
int v[5] = {1, 2, 3, 4, 5}
/*
v[0] = 1
v[1] = 2
v[2] = 3
v[3] = 4
v[4] = 5
*/
v = {5, 4, 3, 2, 1};
/*
v[0] = 5
v[1] = 4
v[2] = 3
v[3] = 2
v[4] = 1
*/
Observations:
- If we are going to declare all the elements of the vector in its declaration, we can omit the size, as it will adjust to the number of elements present within the braces:
int x[] = {1, 2, 3}; // x has 3 elements
int y[] = {12, 15, 18, 21}; // y has 4 elements
- If the number of elements inside the braces is smaller than the number of elements, then the positions at the end of the vector will be filled with the value
(in the case of numeric vectors):
int t[5] = {1, 2, 3};
/*
t[0] = 1
t[1] = 2
t[2] = 3
t[3] = 0
t[4] = 0
*/
- To initialize a vector with the value
in all its positions, we can use the logic of the observation above and not put any element inside the braces:
int z[3] = {};
/*
z[0] = 0;
z[1] = 0;
z[2] = 0;
*/
2. Changing only one element:
int v[5];
v[0] = 7; // first position of the vector
v[4] = 9; // fifth position of the vector
*(v+2) = 123; // third position of the vector
How to read the elements of a vector?
To read the elements of a vector, we can use the scanf command in the following two ways:
1. Using the ampersand ("&") and the [ ] operator indicating the vector position:
int v[7];
scanf("%d", &v[3]); // read the value to be placed in the fourth position of the vector
/*
The use of the ampersand is necessary because, when using the [] operator, we are not
getting the element's address, but accessing the element itself
*/
2. Using pointer arithmetic, without the ampersand:
int v[7];
scanf("%d", v+2); // read the value to be placed in the third position of the vector
/*
The use of the ampersand is not necessary because, when using pointer arithmetic,
we are getting the element's address, since the vector's name is a pointer to its first position
*/
Example
To better illustrate the knowledge learned so far, analyze the example below:
#include <stdio.h>
int main(){
int v[5];
for(int i=0;i<5;i++){
scanf("%d", &v[i]);
}
for(int i=0;i<5;i++){
if(*(v+i) % 2 == 0){
printf("The number at position %d of the vector is even!\n", i);
}
else{
printf("The number at position %d of the vector is odd!\n", i);
}
}
}
Notice that the code above uses a for loop to iterate through all the indices of our vector and read their respective elements using the scanf command.
After that, we again use a for loop to iterate through all the elements of the vector and check, one by one, if they are even or odd.
Conclusion
Throughout this lesson, you learned what vectors are, how they work in the C language, and how to access, fill, and iterate through them efficiently. You also understood that indices always start from zero and that this must be considered when using loops.
Now you are ready to apply vectors in your programs and solve problems involving collections of data in an organized and efficient way! ๐
