Union of Two Arrays in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Union of Two Arrays in C: Program to Find Unique Elements

📑 On this page:
  • Introduction
  • C Program for Union of Two Arrays
  • Sample Output
  • Program Explanation
  • Algorithm
  • Union of Sorted Arrays
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What is the union of two arrays
  • How to find the union of two arrays
  • How to handle duplicates in union
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to find the union of two arrays.

The union of two arrays is a set of all unique elements from both arrays combined. It is used in many real-world applications, such as:

  • Combining two lists of contacts without duplicates
  • Merging two product catalogs
  • Creating a complete list of keywords from multiple documents
  • Combining two datasets for analysis

💡 Key Point: The union of two arrays contains all unique elements from both arrays. Unlike intersection, which only keeps common elements, union includes all elements from both arrays without duplicates.

C Program for Union of Two Arrays

#include <stdio.h>

int main() {
    int n1, n2, i, j, k;
    int count = 0;
    
    // ====== FIRST ARRAY ======
    printf("Enter the number of elements in first array: ");
    scanf("%d", &n1);
    int arr1[n1];
    
    printf("Enter %d elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    // ====== SECOND ARRAY ======
    printf("\nEnter the number of elements in second array: ");
    scanf("%d", &n2);
    int arr2[n2];
    
    printf("Enter %d elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // ====== FIND UNION ======
    // Maximum possible size is n1 + n2
    int union_array[n1 + n2];
    
    // Copy all elements from first array
    for(i = 0; i < n1; i++) {
        union_array[count] = arr1[i];
        count++;
    }
    
    // Add elements from second array that are not already in union
    for(i = 0; i < n2; i++) {
        int duplicate = 0;
        for(j = 0; j < count; j++) {
            if(arr2[i] == union_array[j]) {
                duplicate = 1;
                break;
            }
        }
        if(duplicate == 0) {
            union_array[count] = arr2[i];
            count++;
        }
    }
    
    // ====== DISPLAY ======
    printf("\nFirst array: ");
    for(i = 0; i < n1; i++) {
        printf("%d ", arr1[i]);
    }
    
    printf("\nSecond array: ");
    for(i = 0; i < n2; i++) {
        printf("%d ", arr2[i]);
    }
    
    printf("\n\nUnion of two arrays: ");
    for(i = 0; i < count; i++) {
        printf("%d ", union_array[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output

Enter the number of elements in first array: 5
Enter 5 elements:
10 20 30 40 50

Enter the number of elements in second array: 4
Enter 4 elements:
30 50 60 70

First array: 10 20 30 40 50
Second array: 30 50 60 70

Union of two arrays: 10 20 30 40 50 60 70

Example with Duplicates:

Enter the number of elements in first array: 6
Enter 6 elements:
10 20 10 30 20 40

Enter the number of elements in second array: 5
Enter 5 elements:
10 10 20 50 60

First array: 10 20 10 30 20 40
Second array: 10 10 20 50 60

Union of two arrays: 10 20 30 40 50 60

Example with All Unique Elements:

Enter the number of elements in first array: 3
Enter 3 elements:
10 20 30

Enter the number of elements in second array: 3
Enter 3 elements:
40 50 60

First array: 10 20 30
Second array: 40 50 60

Union of two arrays: 10 20 30 40 50 60

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n1, n2; — sizes of the two arrays
    • int i, j, k; — loop counters
    • int count = 0; — number of elements in the union
  3. Read Arrays: Reads the size and elements of both arrays.
  4. Find Union:
    • Step 1: Copy all elements from the first array into the union array
    • Step 2: For each element in the second array, check if it already exists in the union
    • Step 3: If not a duplicate, add it to the union array
  5. Display Results: Prints both arrays and the union.
  6. Return: return 0; indicates successful program execution.

📝 Note: The union array size is n1 + n2, which is the maximum possible size. The actual size of the union is stored in the count variable.

Algorithm to Find Union of Two Arrays

Step-by-step algorithm:

  1. Start
  2. Read the elements of first array (arr1)
  3. Read the elements of second array (arr2)
  4. Create an empty union array
  5. Copy all elements from arr1 to union array
  6. For each element in arr2:
    • Check if the element already exists in the union array
    • If not present, add it to the union array
  7. Print the union array
  8. End

Union of Sorted Arrays (More Efficient)

If both arrays are sorted, we can find the union in O(n1 + n2) time using a two-pointer approach.

#include <stdio.h>

int main() {
    int n1, n2, i, j, k;
    int count = 0;
    
    printf("Enter the number of elements in first sorted array: ");
    scanf("%d", &n1);
    int arr1[n1];
    printf("Enter %d sorted elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    printf("\nEnter the number of elements in second sorted array: ");
    scanf("%d", &n2);
    int arr2[n2];
    printf("Enter %d sorted elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // Find union using two-pointer technique
    int union_array[n1 + n2];
    i = 0;
    j = 0;
    
    while(i < n1 && j < n2) {
        if(arr1[i] < arr2[j]) {
            // Add arr1[i] if not already added
            if(count == 0 || union_array[count-1] != arr1[i]) {
                union_array[count] = arr1[i];
                count++;
            }
            i++;
        }
        else if(arr1[i] > arr2[j]) {
            // Add arr2[j] if not already added
            if(count == 0 || union_array[count-1] != arr2[j]) {
                union_array[count] = arr2[j];
                count++;
            }
            j++;
        }
        else {
            // Equal elements - add once
            if(count == 0 || union_array[count-1] != arr1[i]) {
                union_array[count] = arr1[i];
                count++;
            }
            i++;
            j++;
        }
    }
    
    // Add remaining elements from first array
    while(i < n1) {
        if(count == 0 || union_array[count-1] != arr1[i]) {
            union_array[count] = arr1[i];
            count++;
        }
        i++;
    }
    
    // Add remaining elements from second array
    while(j < n2) {
        if(count == 0 || union_array[count-1] != arr2[j]) {
            union_array[count] = arr2[j];
            count++;
        }
        j++;
    }
    
    // Display results
    printf("\nFirst array: ");
    for(i = 0; i < n1; i++) {
        printf("%d ", arr1[i]);
    }
    
    printf("\nSecond array: ");
    for(i = 0; i < n2; i++) {
        printf("%d ", arr2[i]);
    }
    
    printf("\n\nUnion of two arrays: ");
    for(i = 0; i < count; i++) {
        printf("%d ", union_array[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output:

Enter the number of elements in first sorted array: 6
Enter 6 sorted elements:
10 20 20 30 40 50

Enter the number of elements in second sorted array: 5
Enter 5 sorted elements:
20 30 50 60 70

First array: 10 20 20 30 40 50
Second array: 20 30 50 60 70

Union of two arrays: 10 20 30 40 50 60 70

How Two-Pointer Union Works

  • Two Pointers: i points to arr1, j points to arr2
  • Compare: If arr1[i] < arr2[j], add arr1[i] and move i
  • If arr1[i] > arr2[j], add arr2[j] and move j
  • If arr1[i] == arr2[j], add the element once and move both pointers
  • Handle Duplicates: Check if the last added element is the same before adding
  • Time Complexity: O(n1 + n2)

Intersection vs Union

Feature Intersection Union
Definition Common elements All unique elements
Example A={1,2,3}, B={2,3,4} → {2,3} A={1,2,3}, B={2,3,4} → {1,2,3,4}
Size ≤ min(n1, n2) ≤ n1 + n2
Use Case Find common items Combine lists without duplicates

Time and Space Complexity

Method Time Complexity Space Complexity
Nested Loop (Unsorted) O(n1 × n2) O(n1 + n2)
Two-Pointer (Sorted) O(n1 + n2) O(n1 + n2)

💻 Practice Exercise

Challenge 1: Find the union of three arrays.

Challenge 2: Find the union of two arrays without using extra space (modify one of the arrays).

🔍 Click to Show Solution for Challenge 2
#include <stdio.h>

int main() {
    int n1, n2, i, j;
    
    printf("Enter the number of elements in first array: ");
    scanf("%d", &n1);
    int arr1[n1];
    printf("Enter %d elements:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &arr1[i]);
    }
    
    printf("Enter the number of elements in second array: ");
    scanf("%d", &n2);
    int arr2[n2];
    printf("Enter %d elements:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &arr2[i]);
    }
    
    // Copy all elements from arr1 to result (using arr1 itself)
    int result_size = n1;
    
    // Add elements from arr2 that are not in arr1
    for(i = 0; i < n2; i++) {
        int duplicate = 0;
        for(j = 0; j < result_size; j++) {
            if(arr2[i] == arr1[j]) {
                duplicate = 1;
                break;
            }
        }
        if(duplicate == 0) {
            arr1[result_size] = arr2[i];
            result_size++;
        }
    }
    
    printf("\nUnion of two arrays: ");
    for(i = 0; i < result_size; i++) {
        printf("%d ", arr1[i]);
    }
    printf("\n");
    
    return 0;
}

Frequently Asked Questions

1. What is the union of two arrays?

The union of two arrays is a set of all unique elements that appear in either array. It combines both arrays and removes duplicates.

2. How do you find the union of two arrays in C?

Copy all elements from the first array into the union. Then, for each element in the second array, check if it already exists in the union. If not, add it.

3. What is the difference between union and intersection?

Union contains all unique elements from both arrays. Intersection contains only the elements that appear in both arrays.

4. How do you handle duplicates in union?

Before adding an element to the union, check if it already exists in the union array. If it does, skip it. This ensures all elements are unique.

5. Can I find union without using extra space?

Yes, you can store the union in one of the original arrays by first copying all elements from the other array and then removing duplicates.

💡 Tip: If both arrays are sorted, use the two-pointer approach for a more efficient O(n1 + n2) solution.

📖 Related Tutorials

  • Intersection of Two Arrays
  • Remove Duplicate Elements from Array
  • Merge Two Arrays in C
  • More Array Assignments

Previous Topic: -->> Intersection of Two Arrays   ||   Next topic: -->> Shift Array Elements Left


📚 Explore More Topics

🗄️ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

☕ Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.