Set Union and Intersection in C — Array Program with Examples

A set is a collection of distinct elements — no duplicates, order irrelevant. The two operations every course asks you to implement in C are union (A ∪ B: every element that appears in A or B) and intersection (A ∩ B: only the elements that appear in both). This page implements them cleanly over arrays, with a shared contains() helper, duplicate-proof input, and the empty-set edge case handled — all in tested, warning-free C89.

How It Works — Step by Step

  1. Read both sets, silently dropping duplicate input values — a set never stores the same element twice.
  2. Union: copy all of A into the result, then append each element of B that is not already in A (checked with contains()).
  3. Intersection: walk A and keep each element that is found in B.
  4. An intersection can legitimately be empty (disjoint sets) — the program prints { } (empty set) instead of nothing.
Operation Definition A = {1,2,3,4,5}, B = {3,4,5,6,7}
Union A ∪ B in A or B (or both) {1,2,3,4,5,6,7}
Intersection A ∩ B in both A and B {3,4,5}

C Program for Set Union and Intersection

#include <stdio.h>

#define MAX 20

static int contains(const int arr[], int len, int value)
{
    int i;

    for (i = 0; i < len; i++) {
        if (arr[i] == value) {
            return 1;
        }
    }
    return 0;
}

static int read_set(const char *label, int set[])
{
    int n, i, x, len = 0;

    printf("Enter the number of elements in %s: ", label);
    if (scanf("%d", &n) != 1 || n < 0 || n > MAX) {
        return -1;
    }
    printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++) {
        if (scanf("%d", &x) != 1) {
            return -1;
        }
        if (!contains(set, len, x)) {    /* a set never stores duplicates */
            set[len++] = x;
        }
    }
    return len;
}

static void print_set(const int set[], int len)
{
    int i;

    if (len == 0) {
        printf("{ } (empty set)\n");
        return;
    }
    printf("{ ");
    for (i = 0; i < len; i++) {
        printf("%d ", set[i]);
    }
    printf("}\n");
}

int main(void)
{
    int a[MAX], b[MAX], un[2 * MAX], in[MAX];
    int la, lb, lu = 0, li = 0, i;

    la = read_set("set A", a);
    if (la < 0) {
        printf("Invalid input.\n");
        return 1;
    }
    lb = read_set("set B", b);
    if (lb < 0) {
        printf("Invalid input.\n");
        return 1;
    }

    for (i = 0; i < la; i++) {           /* union: everything in A ... */
        un[lu++] = a[i];
    }
    for (i = 0; i < lb; i++) {           /* ... plus B's elements not in A */
        if (!contains(a, la, b[i])) {
            un[lu++] = b[i];
        }
    }
    for (i = 0; i < la; i++) {           /* intersection: in A and in B */
        if (contains(b, lb, a[i])) {
            in[li++] = a[i];
        }
    }

    printf("\nSet A:                ");
    print_set(a, la);
    printf("Set B:                ");
    print_set(b, lb);
    printf("Union (A u B):        ");
    print_set(un, lu);
    printf("Intersection (A n B): ");
    print_set(in, li);
    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra -o sets sets.c
./sets

Sample Input and Output

Test 1 — overlapping sets:

Enter the number of elements in set A: 5
Enter 5 elements: 1 2 3 4 5
Enter the number of elements in set B: 5
Enter 5 elements: 3 4 5 6 7

Set A:                { 1 2 3 4 5 }
Set B:                { 3 4 5 6 7 }
Union (A u B):        { 1 2 3 4 5 6 7 }
Intersection (A n B): { 3 4 5 }

Test 2 — disjoint sets, plus a duplicate in the input (the second 1 is dropped on read):

Enter the number of elements in set A: 4
Enter 4 elements: 1 1 2 3
Enter the number of elements in set B: 2
Enter 2 elements: 8 9

Set A:                { 1 2 3 }
Set B:                { 8 9 }
Union (A u B):        { 1 2 3 8 9 }
Intersection (A n B): { } (empty set)

Code Explanation

  • contains() — one linear-search helper powers deduplication, union, and intersection alike. Writing it once beats the 2012 version’s three copy-pasted flag loops.
  • read_set() — returns the actual stored length, which may be less than the count the user typed if duplicates were entered. Returning −1 signals bad input.
  • un[2 * MAX] — worst case (disjoint sets) the union holds every element of both, so the result array must be twice the size. Getting this bound wrong is a classic buffer overflow.
  • print_set() — treats the empty set as a first-class result, not an error.

Time and Space Complexity

Aspect Complexity Why
Union / intersection O(m × n) each element of one set is linear-searched in the other
With sorted arrays O(m + n) merge-style two-pointer walk — worth mentioning in interviews
Space O(m + n) result arrays

What This Program Teaches

  • Enforcing an invariant (no duplicates) at the input boundary, so later code can rely on it
  • Factoring repeated searches into one helper function
  • Sizing result buffers for the worst case, not the typical case
  • The O(m×n) → O(m+n) improvement path via sorting — the standard follow-up question

Related C Programs

Test yourself: our free C Programming Quiz app for Android has 150+ questions with explanations for every answer.

Recommended Book

The C Programming Language by Kernighan & Ritchie remains the definitive C reference — we’ve solved all of its exercises. Also on Amazon.com.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>