You can solve the problem, only added to vetC
whenever you know that the element does not already exist in vetC
. To simplify, we can start by constructing a function that performs the verification:
int existe(int* vetor, int tamanho, int elemento){
int i;
for (i = 0; i < tamanho; ++i){
if (vetor[i] == elemento) return 1;
}
return 0;
}
Notice two important details of this function:
- The return type was marked with
int
when it is used as 1
or 0
, true or false. This is because in C we do not have natively booleans.
- The size of the vector has to be passed as a parameter because there is no way to know it within the function.
Now in main
we go through the two vectors vetA
and vetB
and only add if they do not already exist:
int tamC = 0;
for (i = 0; i < 5; ++i){
//se vetA[i] ainda não existe em vetC adiciona a vetC e aumenta a quantidade
if (!existe(vetC, tamC, vetA[i])) vetC[tamC++] = vetA[i];
if (!existe(vetC, tamC, vetB[i])) vetC[tamC++] = vetB[i];
}
Notice that only if it does not exist it is added in vetC
and incremented the tamC
variable. This means that at the end of for
, tamC
indicates the actual size of vetC
taking into account duplicate elements that have not been inserted.
This solution adds elements of A and B interleaved. If you want to keep the original order, with all of A and then all of B, you have to separate by 2% with%:
for (i = 0; i < 5; ++i)
if (!existe(vetC, tamC, vetA[i])) vetC[tamC++] = vetA[i];
for (i = 0; i < 5; ++i)
if (!existe(vetC, tamC, vetB[i])) vetC[tamC++] = vetB[i];
If the size of the vectors is an initially defined constant then it is best to make this explicit with a for
eg:
#define TAMANHO 5
View the program with these Ideone changes
Final note: This solution is quadratic (O (n²)) and therefore may not work if the input is gigantic. In this case you can opt for another more efficient solution, even if it involves pre-processing the input data.