Page 312 - Cs_withBlue_J_C11_Flipbook
P. 312

Program 15     Write a program in Java 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()
                 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]+ " ");





                310310  Touchpad Computer Science-XI
   307   308   309   310   311   312   313   314   315   316   317