Array – Mixing values from two arrays into a new array

Two single dimensional arrays contain the elements as follows:
int[] abc={ 9, -3, 5, 0, 3, 8, 2, 17 };
int[] xyz={ 20, 40, 60, 15, 7};

Write a program in Java to initialize the above two arrays to produce a third array lmn[] which contains the values from the two arrays in the following sequence:
lmn[] = { 9, 20, -3, 40, 5, 60, 0, 15, 3, 7, 8, 2, 17 };

Print the values stored in the array lmn[].

class Merge2Arrays
{
    public static void main(String args[])
    {
        int[] abc={9, -3, 5, 0, 3, 8, 2, 17};
        int[] xyz={20, 40, 60, 15, 7};
        
        //get the lengths of both arrays
        int l1=abc.length;
        int l2=xyz.length;
        
        //create the new array
        int[] lmn=new int[l1+l2];
        int min=(l1<l2)?l1:l2;
        
        //saving values of both arrays into the new array
        int i,k=0;
        for(i=0; i<min; i++)
        {
            lmn[k++]=abc[i];
            lmn[k++]=xyz[i];
        }
        
        //for remaining values
        if(l1>l2)
        {
            for(int j=i;j<l1;j++)
                lmn[k++]=abc[j];
        }
        else if(l2>l1)
        {
            for(int j=i;j<l2;j++)
                lmn[k++]=xyz[j];
        }
        
        //Print the 1st and 2nd arrays
        System.out.print("abc[] = ");
        for(int j=0; j<abc.length; j++)
        {
            System.out.print(abc[j] + ", ");
        }
        
        System.out.print("\nxyz[] = ");
        for(int j=0; j<xyz.length; j++)
        {
            System.out.print(xyz[j] + ", ");
        }
        
        //Print the final array
        System.out.print("\nlmn[] = ");
        for(int j=0; j<lmn.length; j++)
        {
            System.out.print(lmn[j] + ", ");
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *