Page 347 - ComputerScience_Class_11
P. 347

11.5 INSERTION
                 An element can be added to an array even after its declaration. Insertion is the process of adding an element at any
                 desired position in the array. For the insertion of a new value into the array, we should have the value to be inserted as
                 well as the index of the position where the value has to be inserted.The last index of the array should be empty before
                 applying this technique.
                 The following steps are undertaken in this technique:
                 •  Accept the value to be inserted into the array from the user.

                 •  Accept the position (index) from the user where the number has to be inserted in the array.
                 •  Shift all the numbers from the given index to the right one by one.
                 •  Insert the number at the given index.

                        Note:  The last value of the array will be lost as a result of the moving of the index to the right during
                        insertion of the new value.


                 Suppose, the number 20 is to be inserted at index position 1.
                 Step 1:

                                     Index         0          1           2           3           4
                                       Ar         10          5           14          7

                        Here, 20 is to be inserted at position 1.
                 Step 2:

                                     Index         0          1           2           3           4
                                       Ar         10                      5          14           7

                        All the numbers from index 1 to 4 are shifted to the right one by one.

                 Step 3:

                                     Index         0          1           2           3           4
                                       Ar         10          20          5          14           7
                        20 is inserted at index position 1.


                   Program 13    Write a Java program to insert 9 numbers in an array of size 10. Accept the index position
                                 where a number is to be inserted using insertion logic.

                   1       import java.util.*;
                   2       class insertion

                   3       {
                   4           public static void main(String args[])
                   5           {

                   6               Scanner sc= new Scanner(System.in);
                   7               int ar[ ]=new int[5];
                   8               int i, j, n, pos=-1;





                                                                                                           Arrays  345
   342   343   344   345   346   347   348   349   350   351   352