Home / Programs / C Program to Merge Two arrays in C Programming
🚀 Programming Example

C Program to Merge Two arrays in C Programming

👁 5,810 Views
💻 Practical Program
📘 Step Learning
C Program to Merge Two arrays in C Programming

💻 Program Code

/* 
C Program to Merge Two arrays in C Programming
Author: Atnyla Developer

*/


#include<stdio.h>
 
int main() {
 int arr1[30], arr2[30], res[60];
 int i, j, k, n1, n2;
 
 printf("\nEnter no of elements in 1st array :");
 scanf("%d", &n1);
 for (i = 0; i < n1; i++) {
 scanf("%d", &arr1[i]);
 }
 
 printf("\nEnter no of elements in 2nd array :");
 scanf("%d", &n2);
 for (i = 0; i < n2; i++) {
 scanf("%d", &arr2[i]);
 }
 
 i = 0;
 j = 0;
 k = 0;
 
 // Merging starts
 while (i < n1 && j < n2) {
 if (arr1[i] <= arr2[j]) {
 res[k] = arr1[i];
 i++;
 k++;
 } else {
 res[k] = arr2[j];
 k++;
 j++;
 }
 }
 
 /* Some elements in array 'arr1' are still remaining
 whereas the array 'arr2' is exhausted */
 
 while (i < n1) {
 res[k] = arr1[i];
 i++;
 k++;
 }
 
 /* Some elements in array 'arr2' are still remaining
 where as the array 'arr1' is exhausted */
 
 while (j < n2) {
 res[k] = arr2[j];
 k++;
 j++;
 }
 
 //Displaying elements of array 'res'
 printf("\nMerged array is :");
 for (i = 0; i < n1 + n2; i++)
 printf("%d ", res[i]);
 
 return (0);
 
}
                        

🖥 Program Output


Enter no of elements in 1st array :5
1
2
3
4
5

Enter no of elements in 2nd array :5
10
11
12
13
14

Merged array is :1 2 3 4 5 10 11 12 13 14 
                            

📘 Explanation

C Program to Merge Two arrays in C Programming
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.