Page 349 - ComputerScience_Class_11
P. 349

11.6 DELETION
                 An element can be deleted from the array at any time. Deletion is the process of deleting or removing an element from
                 the array from the given position. In this technique, the index position is taken from the user and then the value found
                 at that index is deleted. Also, the number to be deleted can also be taken from the user.

                 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 Java program 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(String args[])

                   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++)





                                                                                                           Arrays  347
   344   345   346   347   348   349   350   351   352   353   354