Merge two arrays
C program to merge two one dimensional arrays elements.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void merge(int a[MAX], int n1, int b[MAX], int n2, int c[MAX*2])
{
int i, j;
for(i=0;i<n1;i++)
{
c[i] = a[i];
}
for(j=0;j<n2;j++)
{
c[i] = b[j];
i++;
}
}
void main()
{
int arr1[MAX], arr2[MAX], arr3[MAX*2];
int n1, n2;
printf("Enter the number of elements in first array\t:");
scanf("%d",&n1);
printf("Enter the elements of the array\n");
read_array(arr1, n1);
printf("Enter the number of elements in second array\t:");
scanf("%d",&n2);
printf("Enter the elements of the array\n");
read_array(arr2, n2);
merge(arr1, n1, arr2, n2, arr3);
printf("\nMerged array\n");
print_array(arr3, n1+n2);
getch();
}
Output
Enter the number of elements in first array :5
Enter the elements of the array
Element 1 :12
Element 2 :25
Element 3 :56
Element 4 :69
Element 5 :98
Enter the number of elements in second array :4
Enter the elements of the array
Element 1 :85
Element 2 :54
Element 3 :41
Element 4 :15
Merged array
Element 1 :12
Element 2 :25
Element 3 :56
Element 4 :69
Element 5 :98
Element 6 :85
Element 7 :54
Element 8 :41
Element 9 :15