C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Merge Two Arrays

Learn how to merge two arrays using a clear C program.

BeginnerArraysMergeSequential copy

PROBLEM UNDERSTANDING

Input and expected output

Sample input
3
1 3 5
4
2 4 6 8
Sample output
1 3 5 2 4 6 8

COMPLETE C PROGRAM

Complete C implementation

merge-two-arrays.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int firstSize, secondSize, first[50], second[50], merged[100];

    scanf("%d", &firstSize);
    if (firstSize < 0 || firstSize > 50) return 1;
    for (int index = 0; index < firstSize; index++) scanf("%d", &first[index]);
    scanf("%d", &secondSize);
    if (secondSize < 0 || secondSize > 50) return 1;
    for (int index = 0; index < secondSize; index++) scanf("%d", &second[index]);
    for (int index = 0; index < firstSize; index++) merged[index] = first[index];
    for (int index = 0; index < secondSize; index++) merged[firstSize + index] = second[index];
    for (int index = 0; index < firstSize + secondSize; index++)
        printf("%d%c", merged[index], index == firstSize + secondSize - 1 ? '\n' : ' ');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

1 3 5 2 4 6 8
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Copy the first array, then append the second array starting at the first array's size.
  3. Display the computed result.

Copy the first array, then append the second array starting at the first array's size.

EFFICIENCY

Time and space complexity

Time complexity

O(n)

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.