×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to merge Two One Dimensional Arrays elements

This program will read Two One Dimensional Array of same data type (integer type) and merge them into another One Dimensional Array of same type.

Merging Two One Dimensional Arrays elements

To merge array elements we have to copy first array's elements into third array first then copy second array's elements into third array after the index of first array elements.

Merge Two One Dimensional Arrays using C program

/*Program to merge two arrays*/
#include <stdio.h>

/** funtion :   readArray() 
    input   :   arr ( array of integer ), size 
    to read ONE-D integer array from standard input device (keyboard). 
**/
void readArray(int arr[], int size)
{
    int i = 0;

    printf("\nEnter elements : \n");

    for (i = 0; i < size; i++) {
        printf("Enter arr[%d] : ", i);
        scanf("%d", &arr[i]);
    }
}

/** funtion :   printArray() 
    input   :   arr ( array of integer ), size 
    to display ONE-D integer array on standard output device (moniter). 
**/
void printArray(int arr[], int size)
{
    int i = 0;

    printf("\nElements are : ");

    for (i = 0; i < size; i++) {
        printf("\n\tarr[%d] : %d", i, arr[i]);
    }
    printf("\n");
}

void merge(int arr1[], int size1, int arr2[], int size2, int arr3[])
{
    int i = 0, j = 0;

    for (i = 0; i < size1; i++)
        arr3[i] = arr1[i];

    for (i = 5, j = 0; i < size2 + 5; i++, j++)
        arr3[i] = arr2[j];
}

int main()
{
    int arr1[5];
    int arr2[5];
    int arr3[10];

    readArray(arr1, 5);
    readArray(arr2, 5);

    merge(arr1, 5, arr2, 5, arr3);

    printArray(arr3, 10);

    return 0;
}

Output

Enter elements : 
Enter arr[0] : 12 
Enter arr[1] : 23 
Enter arr[2] : 34 
Enter arr[3] : 45 
Enter arr[4] : 56 

Enter elements : 
Enter arr[0] : 11 
Enter arr[1] : 22 
Enter arr[2] : 33 
Enter arr[3] : 44 
Enter arr[4] : 55 

Elements are : 
	arr[0] : 12 
	arr[1] : 23 
	arr[2] : 34 
	arr[3] : 45 
	arr[4] : 56 
	arr[5] : 11 
	arr[6] : 22 
	arr[7] : 33 
	arr[8] : 44 
	arr[9] : 55 

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





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