Page 295 - Cs_withBlue_J_C11_Flipbook
P. 295

The following steps are to be taken in the Linear Search technique:
                 Step 1:  Checks ar[0]  i.e., 2  == 5: The condition is false

                 Step 2:  Checks ar[1]  i.e., 4  == 5: The condition is false
                 Step 3:  Checks ar[2]  i.e., 5  == 5: The condition is true and the loop terminates.

                 Though it searches from the first position to the last position and there may be chances that the number to be found
                 is present at the last position. It can be cumbersome for large arrays. Thus, it is considered a slow technique.


                   Program 8     Write a program in Java to input ‘n’ numbers in an array and a number to search and print
                                 whether the number is present in the array or not. (Use Linear Search technique)

                   1       import java.util.*;
                   2       class linear_search

                   3       {
                   4           public static void main()

                   5           {
                   6               Scanner sc=new Scanner(System.in);
                   7               int size;

                   8               System.out.println("Enter size of array: ");

                   9               size=sc.nextInt();
                   10              int ar[ ] = new int[size];
                   11              int ns, i, pos=-1;

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

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

                   15                  ar[i] =sc.nextInt();

                   16              }
                   17              System.out.print("Enter a number to search: ");

                   18              ns=sc.nextInt();
                   19              for(i=0; i<size; i++)

                   20              {
                   21                    if(ar[i]==ns)

                   22                  {
                   23                         pos=i;

                   24                         break;
                   25                  }

                   26              }
                   27              if(pos!=-1)



                                                                                                                       293
                                                                                                              Arrays   293
   290   291   292   293   294   295   296   297   298   299   300