Search This Blog

Sunday, 9 February 2014

linear searching of data in an array in java

/* linear searching of data in an array  */


import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 *
 * @author sanjay kumar singh
 */
public class Linear_Searching
{
     public static void main(String[] args)
     {
         try
         {
             int n,val,pos=0,i,flag=0;
             int []ar=new int[10];
             InputStreamReader ins=new InputStreamReader(System.in);
            BufferedReader br=new BufferedReader(ins);
        System.out.println("Enter the total no of elements :");
        n=Integer.parseInt(br.readLine());
        System.out.println("Enter elements : ");
        for(i=0;i<n;i++)
        {
            ar[i]=Integer.parseInt(br.readLine());
        }
        System.out.println("Elements are :" );
        for(i=0;i<n;i++)
        {
            System.out.print(ar[i]+" ");
        }
        System.out.println("\n");
        System.out.println("Enter the element u want to search:");
        val=Integer.parseInt(br.readLine());
        for(i=0;i<n;i++)
        {
            if(ar[i]==val)
            {
                pos=i;
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            System.out.println("Element is found and its location is : "+(pos+1));
        }
        else
            System.out.println("Element not found");
            
         }
         catch(Exception e)
         {
             System.out.println(e.getMessage()); 
         }
     }
}

Output


Enter the total no of elements :
5
Enter elements : 
2
4
1
7
8
Elements are :
2 4 1 7 8 

Enter the element u want to search:
4
Element is found and its location is : 2

No comments:

Popular Posts