Page 284 - computer science (868) class 11
P. 284

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 program in Java 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()
                 5           {

                 6               Scanner sc= new Scanner(System.in);
                 7               int ar[ ]=new int[10];

                 8               int i, j, n, pos=-1;
                 9               for (i=0; i<9; i++)

                10               {
                11                   System.out.print("Enter a number in the array: ");

                12                   ar[i] =sc.nextInt();



                282282  Touchpad Computer Science-XI
   279   280   281   282   283   284   285   286   287   288   289