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?

2 Answers

1
pmg On

When interpreted as "print from a1 if not present in a2":

#include <stdio.h>

int main(void) {
    int a1[] = {1, 2, 3, 4, 5, 6, 7, 8};
    int a2[] = {1, 3, 5, 7};
    printf("elements of a1 not present in a2:");
    for (int i = 0; i < sizeof a1 / sizeof *a1; i++) {
        int found = 0;
        for (int j = 0; j < sizeof a2 / sizeof *a2; j++) {
            if (a1[i] == a2[j]) { found = 1; break; }
        }
        if (!found) printf(" %d", a1[i]);
    }
    puts("");
    return 0;
}

See code running on ideone

1
Obid On

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