Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to create an array containing all elements that are included in both other two arrays in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>

#define MAX_SIZE 128

// Function to check if a value is in an array
bool contains(int* arr, int size, int val) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == val)
            return true;
    }
    return false;
}

// Function to compute the intersection of two arrays
int getIntersection(int* arr1, int size1, int* arr2, int size2, int* result) {
    int resultSize = 0;

    for (int i = 0; i < size1; i++) {
        if (contains(arr2, size2, arr1[i]) && !contains(result, resultSize, arr1[i])) {
            result[resultSize++] = arr1[i];
        }
    }

    return resultSize;
}

int main() {
    int vec1[] = {1, 1, 2, 3, 4, 4, 5};
    int vec2[] = {4, 5, 3, 3, 6, 7, 8, 8, 8};
    int result[MAX_SIZE];

    int size1 = sizeof(vec1) / sizeof(vec1[0]);
    int size2 = sizeof(vec2) / sizeof(vec2[0]);

    int resultSize = getIntersection(vec1, size1, vec2, size2, result);

    printf("Result: ");
    for (int i = 0; i < resultSize; i++) {
        printf("%d ", result[i]);
    }

    return 0;
}



/*
run:

Result: 3 4 5 

*/

 



answered Jul 6, 2025 by avibootz
...