OneBite.Dev - Coding blog in a bite size

merge multiple array in C

Code snippet on how to merge multiple array in C

  // Merging Two Arrays
  int arr1[] = {1, 2, 3};
  int arr2[] = {4, 5, 6};
  int arr3[6];
  int i, j = 0;

  // Merging the two arrays
  for (i = 0; i < 3; i++) {
    arr3[j] = arr1[i];
    j++;
    arr3[j] = arr2[i];
    j++;
  }

  // Print the merged array
  for (i = 0; i < 6; i++)
    printf("%d ", arr3[i]);

This code is intended to merge two arrays and print the merged result. The two arrays that we want to merge are [1,2,3] and [4,5,6]. We declare our merged array as arr3[6] and loop through arr1, arr2 with two iterators, i and j. In the loop, we assign arr1[i] to arr3[j] and increment j. Then we assign arr2[i] to arr3[j] and increment j. Finally, we print arr3 which contains all items of arr1 and arr2 in the same sequence.

c