Explanatory Question
Write code to merge two sorted arrays?
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
#include int main() { int n1, n2, i = 0, j = 0, k = 0; // Input sizes printf("Enter size of first sorted array: "); scanf("%d", &n1); printf("Enter size of second sorted array: "); scanf("%d", &n2); int arr1[n1], arr2[n2], merged[n1 + n2]; // Input first array printf("Enter elements of first sorted array:\n"); for (i = 0; i < n1; i++) { scanf("%d", &arr1[i]); } // Input second array printf("Enter elements of second sorted array:\n"); for (i = 0; i < n2; i++) { scanf("%d", &arr2[i]); } // Reset indices i = j = k = 0; // Merge logic while (i < n1 && j < n2) { if (arr1[i] <= arr2[j]) { merged[k++] = arr1[i++]; } else { merged[k++] = arr2[j++]; } } // Copy remaining elements while (i < n1) { merged[k++] = arr1[i++]; } while (j < n2) { merged[k++] = arr2[j++]; } // Output merged array printf("Merged sorted array:\n"); for (i = 0; i < n1 + n2; i++) { printf("%d ", merged[i]); } return 0; }
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.