Can solve the problem, added only to vetC whenever you know that the element does not yet exist in vetC. To simplify we can start by building a function that does the checking:
int existe(int* vetor, int tamanho, int elemento){
int i;
for (i = 0; i < tamanho; ++i){
if (vetor[i] == elemento) return 1;
}
return 0;
}
Note 2 important details of this function:
- The type of return was marked with
int when it is used as 1 or 0, true or false. This is because in C we do not natively have booleans.
- The size of the vector had to be passed as parameter because there is no way to know inside the function.
Now on the main the two vectors are traversed vetA and vetB and is only added if no longer exists:
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];
}
Note that only if it does not exist is added to vetC and incremented the variable tamC. This means that at the end of the for, tamC indicates the actual size of vetC taking into account the duplicated elements which have not been inserted.
This solution adds elements of A and B interchangeably. If you want to keep the original order, with all of A and then all of B, you have to separate into 2 for:
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 better to make this explicit with a #define for example:
#define TAMANHO 5
View the program with these changes in Ideone
Final note: This solution is quadratic (O(n²)) and therefore may not serve if the data entry is gigantic. In this case, you can choose another more efficient solution, even if it involves pre-processing the input data.
Related: https://answall.com/a/236929/64969
– Jefferson Quesado
"do not print repeated numbers" - I think what you mean is to construct a resultant vector without certain repeated numbers ?
– Isac
@Isac want the vector C not print 2x the same number type I type the number 1 in vector A and B but will only print the number 1 only once will not repeat.
– Gustavo Carvalho