Merge Array - Coder's point

Saturday, March 16, 2019

Merge Array

 import java.util.*;  
 public class merge_array  
 {  
   void merge()  
   {  
     int i,j,k;  
     int n1, n2, size;  
     int arr1[] = new int[50];  
     int arr2[] = new int[50];  
     int merge[] = new int[100];  
     Scanner in = new Scanner(System.in);  
     System.out.print("Enter Array 1 Size : ");  
     n1 = in.nextInt();      
     System.out.print("Enter Array 1 Elements : ");  
     for(i=0; i<n1; i++)  
     {  
       arr1[i] = in.nextInt();  
     }  
     System.out.print("Enter Array 2 Size : ");  
     n2 = in.nextInt();  
     System.out.print("Enter Array 2 Elements : ");  
     for(i=0; i<n2; i++)  
     {  
       arr2[i] = in.nextInt();  
     }  
     System.out.print("Merging the Arrays...\n");  
     for(i=0; i<n1; i++)  
     {  
       merge[i] = arr1[i];  
     }  
     size = n1 + n2;  
     for(i=0, k=n1; k<size && i<n2; i++, k++)  
     {  
       merge[k] = arr2[i];  
     }  
     System.out.print("Now the New Array after Merging is :\n");  
     for(i=0; i<size; i++)  
     {  
       System.out.print(merge[i] + " ");  
     }  
   }  
   public static void main(String args[])  
   {  
     merge_array ob=new merge_array();  
     ob.merge();  
   }  
 }  
OUTPUT
Enter Array 1 Size : 5
Enter Array 1 Elements : 4 5 6 3 5 
Enter Array 2 Size : 5
Enter Array 2 Elements : 1 2 3 4 9
Merging the Arrays...
Now the New Array after Merging is :
4  5  6  3  5  1  2  3  4  9  

No comments:

Post a Comment