×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to merge two arrays in third array which is creating dynamically

In this C program, we are merging two one dimensional array in third array, where size of first and second arrays are different and the size of third array will be size of first array + second array.
Submitted by IncludeHelp, on April 14, 2018

Problem statement

Given two dimensional array and we have to merge them in a single array using C program.

Example

First array elements: 10, 20 ,30
Second array elements: 40, 50, 60

Output:
Third array: 10, 20, 30, 40, 50, 60

Program to merge two arrays in C

/** C program to merge two arrays into a new  * array */ #include <stdio.h> #include <stdlib.h> int main() { // declare two int arrays int array_1[30] = {0}; int array_2[30] = {0}; // declare an int pointer which // will store the combination of // array_1 and array_2 int *c; // declare some local variables int i=0 , j=0 , k=0; // x will store the number of elements for array_1 // y will store the number of elements for array_2 // z will store the total number of elements of array_2 array_1 int x=0 , y=0 , z=0; printf("\nEnter the number of elements for both arrays.."); printf("\nFor array_1 : "); scanf("%d",&x); printf("\nFor array_2 : "); scanf("%d",&y); printf("\nEnter the elements for array_1..\n"); for(i=0 ; i<x ; i++) { printf("array_1[%d] : ",i); scanf("%d",&array_1[i]); } printf("\nEnter the elements for array_2..\n"); for(i=0 ; i<x ; i++) { printf("array_2[%d] : ",i); scanf("%d",&array_2[i]); } // Calculate the total elements for pointer "c" z = x +y; printf("\nTotal elements are : %d\n",z); // now allocate dynamic memory to pointer "c" // but according to the "z" c = (int*)malloc(z * sizeof(int)); for(i=0,j=0,k=0 ; i<z,j<x,k<y ; i++) { c[i] = array_1[j++]; if(i>=x) { c[i] = array_2[k++]; } } printf("\nThe final array after merging the two arrays is.."); for(i=0;i<z;i++) { printf("\nC[%d] : %d",i,c[i]); } return 0; }

ADVERTISEMENT

Output

Enter the number of elements for both arrays..   
For array_1 : 3  
 
For array_2 : 3  
 
Enter the elements for array_1.. 
array_1[0] : 10  
array_1[1] : 20  
array_1[2] : 30  
 
Enter the elements for array_2.. 
array_2[0] : 40  
array_2[1] : 50  
array_2[2] : 60  
 
Total elements are : 6
   
The final array after merging the two arrays is..
C[0] : 10
C[1] : 20
C[2] : 30
C[3] : 40
C[4] : 50
C[5] : 60

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.