In this tutorial you will learn about the C Program For Merging Of Two Arrays and its application with practical example.
C Program to Merge Two Arrays
In this tutorial, we will learn to create a C program that will merge two different array the element of Array using C programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- For loop in C Programming.
Merging of two arrays:-
As we all know array is a collection of similar data type elements. In array only one variable is declared which can store multiple values. First will take the number of elements of array1 from the user. Then will take the number of elements of array2 from the user. Then will take the elements from the user for the array1 and as well as for array 2.
And at last, will merge the values and of the different arrays into a single array using C Programming Language.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
STEP 1: START STEP 2: INITIALIZE arr[] = {25, 11, 7, 75, 56} STEP 3: length= sizeof(arr)/sizeof(arr[0]) STEP 4: min = arr[0] STEP 5: SET i=0. PRINT ARRAY i<lenght NORMAL ORDER STEP 6: SET i=lenght -1 THEN PRINT STEP 7: i=i-1. STEP 8: PRINT "REVERSE ORDER OF ARRAY IS AS FOLLOWS" STEP 9: RETURN 0. STEP 10: END. |
Program:-
To find Merge the two array element into single array
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 32 33 34 35 36 37 |
// Online C compiler to run C program online #include <stdio.h> int main() { int n1,n2,n3; //Declaration of Size of Array 1 printf("\nEnter the size of first array \n"); scanf("%d",&n1); //Declaration of Size of Array 2 printf("\nEnter the size of second array \n"); scanf("%d",&n2); n3=n1+n2; printf("\nEnter the first array elements\n"); int a[n1],b[n2],c[n3]; //Declaration of Array for(int i=0;i<n1;i++) //Initialization of Array { scanf("%d",&a[i]); c[i]=a[i]; } int k=n1; printf("\nEnter the second array elements\n"); for(int i=0;i<n2;i++) //Initialization of Array { scanf("%d",&b[i]); c[k]=b[i]; k++; } printf("\nThe merged third array..\n"); for(int i=0;i<n3;i++) printf("%d ",c[i]); //Printing of the merged array return 0; } |
Output:-
The above program we have first initialize the required variable
- a[] = it will hold the elements in a array1.
- b[] = it will hold the elements in a array2.
- c[] = it will hold the elements in a array3.
- n1 = it will hold the number of elements of array1.
- n2 = it will hold the number of elements of array2.
- n3 = it will hold the number of elements of array3.
- i = it will hold the integer value to control array using for loop.
Taking input from the user for array1 as well as array2 and merging them.
Printing merged array.