Write a Java program to search an element using linear(sequential) search using array.

Write a Java program to search an element using linear or sequential search using array.


program:
import java.util.*;
public class Linear_Search
{
public static void main(String args[])

int n,i,key;

int a[] = new int[50];
Scanner sc = new Scanner(System.in);

System.out.println("Enter Total Number of Elements : ");
n = sc.nextInt();

System.out.println("Enter " +n+ " Elements : ");
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}

System.out.println("Enter a keyValue to Search :");
key= sc.nextInt();

//searching
for (i = 0; i< n; i++) 
{
if (a[i] == key) 

System.out.println(key+" is present at location "+(i+1));  
break; 
}
}
if (i== n) 
System.out.println(key+ " doesn't exist in array.");

}


Output :

Enter Total Number of Elements :
5
Enter 5 Elements : 
10
20
40
60
30
Enter a keyValue to Search :
30
30 is present at location 5


Or


Enter Total Number of Elements : 
5
Enter 5 Elements : 
10
40
5
6
3
Enter a keyValue to Search:
7
7 doesn't exist in array.

Comments

Popular posts from this blog

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Write a java program to demonstrate static variable, methods, blocks.