Computer Science, asked by BrainlyProgrammer, 1 month ago

[Challenge]
Create your own cɵde to merge the two array given by the user of any length.

RESTRICTION:-
=> You can use only 3 loops in the whole co-de created by you(each for input, merging and printing)

Shortest co-de Possible.

Answers

Answered by anindyaadhikari13
13

Solution:

I will rather take command line input and then concat them using arraycopy() function.

import java.util.*;

public class Array  {

   public static void main(int a[],int b[])  {

       int x=a.length,y=b.length;

       int c[]=new int[x+y];

       System.arraycopy(a, 0, c, 0, x);

       System.arraycopy(b, 0, c, x,y);

       System.out.println("First Array: "+Arrays.toString(a));

       System.out.println("Second Array: "+Arrays.toString(b));

       System.out.println("Third Array(First + Second): "+Arrays.toString(c));

   }

}

No loop is used here.

But this problem can be solved using user-defined logic too. Here comes the approach.

import java.util.*;

public class Array  {

   public static void main(int a[],int b[])  {

       int x=a.length,y=b.length,z=0,i;

       int c[]=new int[x+y];

       for(i=0;i<x+y;i++){

           if(i<x)

               c[i]=a[i];

           else

               c[i]=b[z++];

       }

       System.out.println("First Array: "+Arrays.toString(a));

       System.out.println("Second Array: "+Arrays.toString(b));

       System.out.println("Third Array(First + Second): "+Arrays.toString(c));

   }

}

Only 1 loop is used.

Note: Both will yield same result but the first approach is shorter than the others.

See attachments for output.

•••♪

Attachments:
Similar questions