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

Intersection of Two Arrays in C: Program to Find Common Elements

📑 On this page:
  • Introduction
  • C Program for Intersection of Two Arrays
  • Sample Output
  • Program Explanation
  • Algorithm
  • Intersection of Sorted Arrays
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • What is intersection of two arrays
  • How to find common elements between two arrays
  • How to handle duplicates in intersection
  • 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 intersection of two arrays.

The intersection of two arrays is a set of elements that are common to both arrays. It is used in many real-world applications, such as:

  • Finding common friends between two users on social media
  • Finding common products in two shopping lists
  • Finding common keywords in two documents
  • Finding common elements in two datasets

💡 Key Point: The intersection of two arrays contains only the elements that appear in both arrays. Duplicates are typically handled by keeping only one occurrence.

C Program for Intersection 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 INTERSECTION ======
    // Maximum possible size of intersection is the smaller array
    int intersection[n1 < n2 ? n1 : n2];
    
    for(i = 0; i < n1; i++) {
        for(j = 0; j < n2; j++) {
            if(arr1[i] == arr2[j]) {
                // Check if element already added to intersection
                int duplicate = 0;
                for(k = 0; k < count; k++) {
                    if(intersection[k] == arr1[i]) {
                        duplicate = 1;
                        break;
                    }
                }
                if(duplicate == 0) {
                    intersection[count] = arr1[i];
                    count++;
                }
                break;  // Found match, no need to continue inner loop
            }
        }
    }
    
    // ====== 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\nIntersection of two arrays: ");
    if(count == 0) {
        printf("No common elements found.");
    } else {
        for(i = 0; i < count; i++) {
            printf("%d ", intersection[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

Intersection of two arrays: 30 50

Example with No Common Elements:

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

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

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

Intersection of two arrays: No common elements found.

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

Intersection of two arrays: 10 20

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 intersection
  3. Read Arrays: Reads the size and elements of both arrays.
  4. Find Intersection:
    • The outer loop iterates through each element of arr1
    • The inner loop checks if the element exists in arr2
    • If found, check if it's already in the intersection (to avoid duplicates)
    • If not a duplicate, add it to the intersection array
    • break out of the inner loop after finding a match
  5. Display Results: Prints both arrays and the intersection.
  6. Return: return 0; indicates successful program execution.

📝 Note: The size of the intersection array is set to the size of the smaller array, as the intersection cannot be larger than the smaller array.

Algorithm to Find Intersection 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 intersection array
  5. For i = 0 to n1-1:
    • For j = 0 to n2-1:
      • If arr1[i] == arr2[j]:
        • Check if arr1[i] is already in intersection
        • If not present, add it to intersection
        • Break from inner loop
  6. Print the intersection array
  7. End

Intersection of Sorted Arrays (More Efficient)

If both arrays are sorted, we can find the intersection 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 intersection using two-pointer technique
    int intersection[n1 < n2 ? n1 : n2];
    i = 0;
    j = 0;
    
    while(i < n1 && j < n2) {
        if(arr1[i] < arr2[j]) {
            i++;
        }
        else if(arr1[i] > arr2[j]) {
            j++;
        }
        else {
            // Equal elements found
            // Check for duplicates in intersection
            int duplicate = 0;
            for(k = 0; k < count; k++) {
                if(intersection[k] == arr1[i]) {
                    duplicate = 1;
                    break;
                }
            }
            if(duplicate == 0) {
                intersection[count] = arr1[i];
                count++;
            }
            i++;
            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\nIntersection of two arrays: ");
    if(count == 0) {
        printf("No common elements found.");
    } else {
        for(i = 0; i < count; i++) {
            printf("%d ", intersection[i]);
        }
    }
    printf("\n");
    
    return 0;
}

Sample Output:

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

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

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

Intersection of two arrays: 30 40 60

How Two-Pointer Intersection Works

  • Two Pointers: i points to arr1, j points to arr2
  • Compare: If arr1[i] < arr2[j], move i forward
  • If arr1[i] > arr2[j], move j forward
  • If arr1[i] == arr2[j], it's a common element
  • Add to intersection and move both pointers
  • Time Complexity: O(n1 + n2)

Time and Space Complexity

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

💻 Practice Exercise

Challenge 1: Modify the program to find the intersection of three arrays.

Challenge 2: Find the intersection 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, k;
    
    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]);
    }
    
    // Find intersection without extra space
    int count = 0;
    for(i = 0; i < n1; i++) {
        for(j = 0; j < n2; j++) {
            if(arr1[i] == arr2[j]) {
                // Check if already in arr1 (first part)
                int duplicate = 0;
                for(k = 0; k < count; k++) {
                    if(arr1[k] == arr1[i]) {
                        duplicate = 1;
                        break;
                    }
                }
                if(duplicate == 0) {
                    // Store intersection in the beginning of arr1
                    arr1[count] = arr1[i];
                    count++;
                }
                break;
            }
        }
    }
    
    printf("\nIntersection of two arrays: ");
    if(count == 0) {
        printf("No common elements found.");
    } else {
        for(i = 0; i < count; i++) {
            printf("%d ", arr1[i]);
        }
    }
    printf("\n");
    
    return 0;
}

Frequently Asked Questions

1. What is the intersection of two arrays?

The intersection of two arrays is a set of elements that appear in both arrays. It contains only the common elements.

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

You can use nested loops to compare each element of the first array with each element of the second array. If a match is found and it's not already in the result, add it to the intersection.

3. What is the difference between intersection and union?

Intersection contains elements common to both arrays. Union contains all unique elements from both arrays combined.

4. How do you handle duplicates in intersection?

Before adding an element to the intersection, check if it's already present. This ensures each element appears only once in the result.

5. Can I find intersection without using extra space?

Yes, you can store the intersection in one of the original arrays by overwriting elements at the beginning of the array.

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

📖 Related Tutorials

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

Previous Topic: -->> Remove Duplicate Elements from Array   ||   Next topic: -->> Union of Two Arrays


📚 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.