Write a C program to create a third array by using two existing sorted array, third array must automaticall get created in sorted order without having duplicacy of number. e.g., array1={4,8,9,12,16,20} array2={1,3,4,5,8,9,14} result={1,3,4,5,8,9,12,14,16,20}

#include<stdio.h>
main()
{   
    int array1[100],array2[100],result[200],n1,n2,i,j,k,f;
    printf("\nEnter number of terms of the first set=");
    scanf("%d",&n1);
    printf("\nEnter the elements of the first set=");
    for(i=0;i<n1;i++)
    {
        scanf("%d",&array1[i]);
    }       
    printf("\nEnter number of terms of the second set=");
    scanf("%d",&n2);
    printf("\nEnter the elements of the second set=");
    for(i=0;i<n2;i++)
    {
        scanf("%d",&array2[i]);
    }
    printf("\nThe elements of the first set=");
    for(i=0;i<n1;i++)
    {
        printf("%d ",array1[i]);
    }
    printf("\nThe elements of the second set=");
    for(i=0;i<n2;i++)
    {
        printf("%d ",array2[i]);
    }
    i=0;
    j=0;
    k=0;
    while(i<n1 && j<n2)
    {
        if(array1[i]==array2[j])
        {
            result[k++]=array1[i++];
            j++;
        }
        else if(array1[i]<array2[j])
            result[k++]=array1[i++];
        else
            result[k++]=array2[j++];
    }
    while(i<n1)
    {
        result[k++]=array1[i++];       
    }
    while(j<n2)
    {
        result[k++]=array2[j++];       
    }       
    printf("\nThe result=");
    for(i=0;i<k;i++)
    {
        printf("%d ",result[i]);
    }   
}

No comments:

Post a Comment