Page 325 - Cs_withBlue_J_C11_Flipbook
P. 325

Program 3     Using the concept of Array, input names of 10 students. Input a name to be deleted and
                                 delete the name from the array, if found, else provide a suitable message.

                   1      import java.util.*;
                   2      class name

                   3      {

                   4          public static void main()
                   5          {
                   6              Scanner sc= new Scanner (System.in);

                   7              int size;
                   8              System.out.println("Enter the number of students " );

                   9              size=sc.nextInt();
                  10              String ar[]=new String[size];

                  11              String nd;
                  12              int i, j, pos=-1;

                  13              for (i=0; i<size; i++)
                  14              {

                  15                  System.out.print("Enter the name of the student: ");
                  16                  ar[i] =sc.next();

                  17              }
                  18              System.out.println("Enter a name to be deleted: ");

                  19              nd=sc.next();
                  20              for(i=0; i<size; i++)

                  21              {
                  22                  if(nd.equalsIgnoreCase(ar[i]))

                  23                  {
                  24                      pos=i;

                  25                      break;
                  26                  }
                  27              }

                  28              if(pos!=-1)

                  29              {
                  30                  for (i=pos; i<size-1; i++) //shifting 1 element to the left
                  31                  {

                  32                      ar[i]=ar[i+1];




                                                                                                                       323
                                                                                                              Arrays   323
   320   321   322   323   324   325   326   327   328   329   330