Merge Two Arrays in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Merge Two Arrays in C: Program to Combine Two Arrays into One

📑 On this page:
  • Introduction
  • C Program to Merge Two Arrays
  • Sample Output
  • Program Explanation
  • Merging Sorted Arrays
  • Practice Exercise
  • Frequently Asked Questions
📚 In this tutorial, you will learn:
  • How to merge two arrays into a single array
  • How to combine elements from both arrays
  • How to merge sorted arrays in order
  • 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 merge two arrays into a single array.

Merging two arrays is a common operation in programming. It is used in many real-world applications, such as:

  • Combining two lists of data (like merging two class lists)
  • Merging sorted arrays (merge sort algorithm)
  • Combining results from multiple sources
  • Database query result merging

💡 Key Point: To merge two arrays, we create a third array with a size equal to the sum of the sizes of the two arrays, then copy all elements from both arrays into it.

C Program to Merge Two Arrays

#include <stdio.h>

int main() {
    int n1, n2, i;
    
    // ====== 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]);
    }
    
    // ====== MERGE ======
    int merged[n1 + n2];
    
    // Copy elements from first array
    for(i = 0; i < n1; i++) {
        merged[i] = arr1[i];
    }
    
    // Copy elements from second array
    for(i = 0; i < n2; i++) {
        merged[n1 + i] = arr2[i];
    }
    
    // ====== 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("\nMerged array: ");
    for(i = 0; i < n1 + n2; i++) {
        printf("%d ", merged[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output

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

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

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

Another Example:

Enter the number of elements in first array: 2
Enter 2 elements:
5 15

Enter the number of elements in second array: 3
Enter 3 elements:
25 35 45

First array: 5 15
Second array: 25 35 45
Merged array: 5 15 25 35 45

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; — loop counter
  3. Read First Array: Reads the size and elements of the first array.
  4. Read Second Array: Reads the size and elements of the second array.
  5. Merge the Arrays:
    • int merged[n1 + n2]; — creates a merged array with total size
    • First loop copies all elements from arr1 into merged
    • Second loop copies all elements from arr2 into merged starting at index n1
  6. Display Results: Prints all three arrays.
  7. Return: return 0; indicates successful program execution.

📝 Note: The merged array's size is n1 + n2. Make sure both source arrays are large enough to hold all elements.

Method 2: Merging Sorted Arrays (Merge Sort Style)

When both arrays are already sorted, we can merge them efficiently in O(n1 + n2) time using a two-pointer approach. This is the core of the merge sort algorithm.

#include <stdio.h>

int main() {
    int n1, n2, i, j, k;
    
    // Read first sorted array
    printf("Enter 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]);
    }
    
    // Read second sorted array
    printf("\nEnter 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]);
    }
    
    // Merge sorted arrays
    int merged[n1 + n2];
    i = 0; j = 0; k = 0;
    
    while(i < n1 && j < n2) {
        if(arr1[i] < arr2[j]) {
            merged[k] = arr1[i];
            i++;
        } else {
            merged[k] = arr2[j];
            j++;
        }
        k++;
    }
    
    // Copy remaining elements from first array
    while(i < n1) {
        merged[k] = arr1[i];
        i++;
        k++;
    }
    
    // Copy remaining elements from second array
    while(j < n2) {
        merged[k] = arr2[j];
        j++;
        k++;
    }
    
    // Display merged array
    printf("\nMerged sorted array: ");
    for(i = 0; i < n1 + n2; i++) {
        printf("%d ", merged[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output:

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

Enter number of elements in second sorted array: 3
Enter 3 sorted elements:
15 25 35

Merged sorted array: 10 15 20 25 30 35 40

How Sorted Array Merge Works

  • Two Pointers: i points to arr1, j points to arr2
  • Compare: Compare arr1[i] and arr2[j], add the smaller one to merged array
  • Advance: Move the pointer of the array from which the element was taken
  • Remaining: After one array is exhausted, copy all remaining elements from the other array
  • Time Complexity: O(n1 + n2)

Algorithm to Merge Two Arrays

  1. Start
  2. Read size and elements of first array (arr1)
  3. Read size and elements of second array (arr2)
  4. Create merged array of size n1 + n2
  5. For i = 0 to n1-1:
    • Set merged[i] = arr1[i]
  6. For j = 0 to n2-1:
    • Set merged[n1 + j] = arr2[j]
  7. Print the merged array
  8. End

💻 Practice Exercise

Challenge 1: Merge two arrays and then remove duplicate elements from the merged array.

Challenge 2: Merge two arrays in alternating order (arr1[0], arr2[0], arr1[1], arr2[1], ...).

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

int main() {
    int n1, n2, i, j = 0;
    
    printf("Enter 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 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]);
    }
    
    // Alternate merge
    int merged[n1 + n2];
    int k = 0;
    int max_size = n1 > n2 ? n1 : n2;
    
    for(i = 0; i < max_size; i++) {
        if(i < n1) {
            merged[k] = arr1[i];
            k++;
        }
        if(i < n2) {
            merged[k] = arr2[i];
            k++;
        }
    }
    
    printf("\nAlternate merged array: ");
    for(i = 0; i < n1 + n2; i++) {
        printf("%d ", merged[i]);
    }
    printf("\n");
    
    return 0;
}

/* Sample Output:
Enter number of elements in first array: 3
Enter 3 elements:
10 20 30
Enter number of elements in second array: 4
Enter 4 elements:
40 50 60 70
Alternate merged array: 10 40 20 50 30 60 70
*/

Frequently Asked Questions

1. How do you merge two arrays in C?

Create a third array with size equal to the sum of the two arrays. Copy all elements from the first array, then copy all elements from the second array into the third array.

2. What is the time complexity of merging two arrays?

The time complexity is O(n1 + n2), where n1 and n2 are the sizes of the two arrays. For sorted arrays, it's also O(n1 + n2).

3. Can I merge two arrays of different data types?

No, arrays must be of the same data type to be merged directly. You would need to create a structure or union to store different types.

4. How do I merge sorted arrays without extra space?

You need extra space to store the merged result. However, you can merge into an existing array if it's large enough using the memcpy function.

5. What is the difference between concatenation and merging?

Concatenation simply joins two arrays one after another. Merging typically refers to combining sorted arrays while maintaining the sorted order.

💡 Tip: When merging sorted arrays, use the two-pointer method for better performance. This is the same algorithm used in merge sort.

📖 Related Tutorials

  • Copy Array Elements in C
  • Reverse an Array in C
  • Sort an Array in Ascending Order
  • More Array Assignments

Previous Topic: -->> Copy Array Elements in C   ||   Next topic: -->> Sort Array in Ascending Order


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