Page 351 - ComputerScience_Class_11
P. 351

Program 15    Write a Java program to create an array of 5 elements. Accept a number and delete the
                                 number by using the deletion logic.
                   1       import java.util.*;
                   2       class deletion2

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

                   11                  System.out.print("Enter a number: ");
                   12                  ar[i] =sc.nextInt();

                   13              }
                   14              System.out.println("Enter a number to be deleted: ");
                   15              n=sc.nextInt();

                   16
                                   for(i=0; i<5; i++)
                   17              {
                   18                  if(n==ar[i])

                   19                  {
                   20                      pos=i;

                   21                      break;
                   22                  }
                   23              }

                   24              if(pos!=-1)
                   25              {
                   26                  for (i=pos; i<4; i++) //shifting 1 element to the left

                   27                  {
                   28                      ar[i]=ar[i+1];

                   29                  }
                   30                  ar[4]=0;
                   31                  for (i=0; i<5; i++)

                   32                  {System.out.print(ar[i]+ " ");
                   33                  }







                                                                                                           Arrays  349
   346   347   348   349   350   351   352   353   354   355   356