Merge of sorted arrays in C: solved exercise

Merge of sorted arrays in C: solved exercise

If you are looking for merge of sorted arrays in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Merge {1,4,7} and {2,3,6,8} in ascending order.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdio.h>

int main(void) {
    int a[] = {1, 4, 7};
    int b[] = {2, 3, 6, 8};
    int c[7];
    int i = 0, j = 0, k = 0;

    while (i < 3 && j < 4) {
        if (a[i] <= b[j]) {
            c[k++] = a[i++];
        } else {
            c[k++] = b[j++];
        }
    }
    while (i < 3) {
        c[k++] = a[i++];
    }
    while (j < 4) {
        c[k++] = b[j++];
    }

    for (int p = 0; p < 7; p++) {
        printf("%d", c[p]);
        if (p + 1 < 7) {
            printf(" ");
        }
    }
    printf("\n");
    return 0;
}

Expected output

1
1 2 3 4 6 7 8

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

The key idea is to identify a reusable pattern instead of stopping at “it works once”.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.