I have got 2 arrays a1 = {1,2,3,4,5,6,7.....}
and a2 = {1,3,5,7}
If I have to exclude the elements of a2
from a1
and print a1
what would be the best way?
How do I exclude elements from an array?
Asked by Vikram Vm At2 Answers
1
Example function which removes all the elements having particular value from the array. This example is for type int
but it is very easy to change any other type
size_t remove_element(int *arr, size_t size, int element)
{
for(size_t index = 0; index < size; )
{
if(arr[index] == element)
{
memmove(arr + index, arr + index + 1, (size - index - 1) * sizeof(*arr));
size --;
continue;
}
index++;
}
return size;
}
int main()
{
int h[] = {4,6,8,9,2,3,0,1,2,5,6,9,0};
size_t size = sizeof(h) / sizeof(h[0]), newsize = remove_element(h, size, 0);
printf("Size Before:%zu New size %zu\n", size, newsize);
for(size_t index = 0; index < newsize; index++)
{
printf("h[%zu] = %d\n", index, h[index]);
}
return 0;
}
and to remove elements which are in another array
size_t remove_elements(int *arr, size_t arrsize, const int *elements, size_t elemsize)
{
for(size_t index = 0; index < elemsize; index++)
{
arrsize = remove_element(arr, arrsize, elements[index])
}
return arrsize;
}
Try yourself: https://onlinegdb.com/ryRJOGNnN
When interpreted as "print from a1 if not present in a2":
See code running on ideone