Page 310 - Cs_withBlue_J_C11_Flipbook
P. 310

In that case, the given number is first checked (for its presence in the array) using any searching technique, and then,
              if it is there in the array it is deleted.
              The following steps are undertaken in this technique:
              •  Accept the position from the user from where the number has to be deleted.
              •  Delete the number at the given position.
              •  After deleting the number, shift all the numbers after the given index one position to the left.
              •  Enter the number 0 at the last index position.

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

                                   Index        0           1           2          3           4
                                    Ar          10          5          14          7           66

                      Here, the number 5 is to be removed.

              Step 2:
                                   Index        0           1           2          3           4
                                    Ar          10          14          7          66          66

                      All the numbers from index 2 to 4 are shifted to the left one by one.

              Step 3:
                                   Index        0           1           2          3           4
                                    Ar          10          14          7          66          0


                      0 is inserted at the last index, else there will be a duplicate value.


                Program 14     Write a program in Java to create an array of 5 elements. Accept the index position and
                               delete the corresponding number by using the deletion logic.
                 1       import java.util.*;

                 2       class deletion1
                 3       {

                 4           public static void main()
                 5           {

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

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

                11                     System.out.print("Enter a number: ");

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



                308308  Touchpad Computer Science-XI
   305   306   307   308   309   310   311   312   313   314   315