Programming Examples
Java program to accept n elements in array and search a specific element using linear search
Write a JAVA program which accept n integer number from user in array and search for specific element that present in array or not, if it present also print the index number first occurrence of search element.
Solution:
import java.util.*;
class LinearSearch
{
public static void main(String arr[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of Array : ");
int n=sc.nextInt();
int num[]=new int[n];
int even=0,odd=0;
System.out.println("Enter the "+n+" Elements of Array");
for(int i=0;i<n;i++)
{
num[i]=sc.nextInt();
}
System.out.println("Enter any number for Search : ");
int ch=sc.nextInt();
boolean found=false;
for(int i=0;i<n;i++)
{
if(num[i]==ch)
{
found=true;
System.out.println("Element Found At "+i+" position(index)");
break;
}
}
if(found==false)
{
System.out.println("Element Not Found");
}
}
}
Output
Enter the size of Array :
5
Enter the 5 Elements of Array
22
33
44
55
66
Enter any number for Search :
55
Element Found At 3 position(index)
Enter the size of Array :
5
Enter the 5 Elements of Array
12
13
14
15
16
Enter any number for Search :
20
Element Not Found