Page 297 - Computer science 868 Class 12
P. 297

9.3.5 Merging of Two Arrays
                 When two arrays are merged, the third array will have the total size of the first and the second array. From the first
                 array, the elements will be copied to the third array, then the elements of the second array will be copied.


                   Program 11    Write a program to merge the arrays in the array at a specific position.


                   1       import java.util.*;
                   2       class merge_array
                   3       {

                   4           int ar1[],ar2[],ar3[];

                   5           int ar1_s,ar2_s,ar3_s;
                   6           void input()
                   7           {

                   8               Scanner sc= new Scanner(System.in);
                   9               System.out.println("Enter the length of the first array");

                   10              ar1_s=sc.nextInt();
                   11              ar1=new int[ar1_s];

                   12              System.out.println("Enter the length of the second array");
                   13              ar2_s=sc.nextInt();

                   14              ar2=new int[ar2_s];
                   15              ar3_s=ar1_s+ar2_s;

                   16              ar3=new int[ar3_s];
                   17              System.out.println("Enter the values for the first array");

                   18              for(int i=0;i<ar1_s;i++)
                   19                  ar1[i]=sc.nextInt();

                   20              System.out.println("Enter the values for the second array");
                   21              for(int i=0;i<ar2_s;i++)

                   22                  ar2[i]=sc.nextInt();
                   23          }

                   24
                   25          void merge()

                   26          {
                   27              for(int i=0;i<ar1_s;i++)
                   28                  ar3[i]=ar1[i];

                   29              for(int i=0;i<ar2_s;i++)

                   30                  ar3[ar1_s+i]=ar2[i];



                                                                                                                       295
                                                                                                              Arrays   295
   292   293   294   295   296   297   298   299   300   301   302