C Program to Merge Two Arrays

1. Introduction

Merging arrays is a common operation in data manipulation. It allows you to combine two arrays into a single array. This tutorial covers a C program that accomplishes this task. We will walk through each step to ensure you have a deep understanding.

2. Program Overview

Our program will perform the following steps:

1. Get the size of the two arrays and their respective elements from the user.

2. Merge these arrays into a third array.

3. Display the merged array.

3. Code Program

#include <stdio.h>  // Standard Input/Output library

int main() {  // Starting the main function.
    int a[50], b[50], merged[100], n1, n2, i;

    // Asking user to input the size and elements of the first array.
    printf("Enter the size of the first array: ");
    scanf("%d", &n1);
    printf("Enter %d elements for the first array:\n", n1);
    for(i = 0; i < n1; i++) {
        scanf("%d", &a[i]);
    }

    // Asking user to input the size and elements of the second array.
    printf("Enter the size of the second array: ");
    scanf("%d", &n2);
    printf("Enter %d elements for the second array:\n", n2);
    for(i = 0; i < n2; i++) {
        scanf("%d", &b[i]);
    }

    // Merging the two arrays.
    for(i = 0; i < n1; i++) {
        merged[i] = a[i];  // First array elements.
    }
    for(i = 0; i < n2; i++) {
        merged[n1+i] = b[i];  // Second array elements.
    }

    // Displaying the merged array.
    printf("Merged array is:\n");
    for(i = 0; i < n1 + n2; i++) {
        printf("%d ", merged[i]);
    }

    return 0;  // Ending the program.
}

Output:

First array size: 3, Elements: 1, 2, 3
Second array size: 2, Elements: 4, 5
The program will display:
Merged array is:
1 2 3 4 5

4. Step By Step Explanation

1. Header Files: We begin by including the stdio.h header, which provides functions for standard input and output.

2. Variable Declaration:

  • Arrays a and b store the elements of the first and second arrays, respectively.
  • Array merged is for the merged array.
  • Variables n1 and n2 will store the sizes of the two arrays.

3. User Input:

  • The user is prompted to provide the size and elements for both arrays.

4. Merging Process:

  • Elements from the first array a are added to the merged array.
  • Elements from the second array b are appended to the merged array, starting from the index immediately after the last element of the first array.

5. Displaying the Merged Array: We loop through the merged array and print its elements.

Combining arrays in this way allows you to concatenate data from different sources or simply manage data more efficiently.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare