Please open the menu to show more

Thursday, August 3, 2017

Solution for the assignment (merging of array based on choice) of 10 to 12 batch given on 3rd, August, 2017

This solution is implemented and provided by 
=>  ITI Dixit 
=>  Computer Science 
=>  Banasthali University (Jaipur)


# save this class inside a Merge.java file #

// inside this class we merge two arrays as per the given user input

import java.util.*;

public class Merge
{
  public static void main(String[] args)
  {
      Scanner sc=new Scanner(System.in);
      System.out.println("ENTER SIZE OF FIRST ARRAY : ");
      int m=sc.nextInt();
 // create an array whose size is equal 'm'
      int[] a=new int[m];
      
 System.out.println("ENTER SIZE OF SECOND ARRAY : ");
      int n=sc.nextInt();
 // create an array whose size is equal 'n'
      int[] b=new int[n];
 
      System.out.println("ENTER ELEMENTS OF FIRST ARRAY : ");
      for(int i=0;i<m;i++) {
          a[i]=sc.nextInt();
 }
 
      System.out.println("ENTER ELEMENTS OF SECOND ARRAY : ");
      for(int i=0;i<n;i++) {
          b[i]=sc.nextInt();
 }
 
      System.out.println("--------------------------------------------");

      System.out.println("ELEMENTS OF FIRST ARRAY are : ");
      for(int i=0;i<m;i++) {
          System.out.println(a[i]);
 }
   
      System.out.println("--------------------------------------------");

      System.out.println("ELEMENTS OF SECOND ARRAY are : ");
      for(int i=0;i<n;i++) {
          System.out.println(b[i]);
 }
 
      System.out.println("--------------------------------------------");

      //declaration of third array with size m+n in which values of both the arrays are to be merged
      int[] c=new int[m+n];      

      //taking user's choice as an input according to the menu
      System.out.println("ENTER YOUR CHOICE : \n 1. B after A \n 2. A after B");
      int ch=sc.nextInt();
      
      int r=0;   
      switch(ch)
      {
          case 1:
             //to store elemnts of array A followed by array B
            for(int i=0;i<m;i++) {
                c[r++]=a[i];
}
            for(int i=0;i<n;i++)  {
                c[r++]=b[i];
}
            System.out.println("MERGED ARRAY : ");
            for(int i=0;i<m+n;i++) {
              System.out.println(c[i]);
            }
            break;
          case 2:
              //to store elemnts of array B followed by array A
              for(int i=0;i<n;i++)  {
                c[r++]=b[i];
 }
 for(int i=0;i<m;i++)  {
                c[r++]=a[i];
 }
 
            System.out.println("MERGED ARRAY : ");
            for(int i=0;i<m+n;i++) {
              System.out.println(c[i]);
}  
            break;
          default:
              System.out.println("INVALID CHOICE");;
            
      }      
  }
}

No comments:

Post a Comment