Linear Search
Write a program to search a given element within an array and display appropriate message if the element was found or not.
import java.util.*;
class LinearSearch
{
public static void main(String args[])throws InputMismatchException
{
Scanner scan=new Scanner(System.in);
int n,i,ele;
boolean flag;
System.out.println("Enter the number of elements : ");
n = scan.nextInt();
int a[] = new int[n]; //declare array
System.out.println("Enter "+n+" elements for the array.");
for(i = 0; i < n; i++)
a[i] = scan.nextInt();
System.out.println("Enter the element to be searched : ");
ele = scan.nextInt();
flag = false;
for(i = 0; i < n; i++){
if(ele == a[i])
{ //if element is found
flag=true; //raise the flag and
break; //break out of loop
}
}
if(flag){
System.out.println("Element is present at position " + (i+1));
}else{
System.out.println("Element not found.");
}
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments