Linear Search Program in Java
import java.util.*;
public class LinearSearch
{
public static void main(String[] args)
{
int n,
pos = -1;
boolean flag = false;
int ar[] = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 10; i++)
{
System.out.print("Enter the number ar[" + i + "]:");
ar[i] = sc.nextInt();
}
System.out.print("Enter number to be search:");
n = sc.nextInt();
for (int i = 0; i < 9; i++)
{
if (ar[i] == n)
{
pos = i + 1;
flag = true;
break;
}
}
if (flag)
{
System.out.println("Position=" + pos);
}
else
{
System.out.println("Number not found.");
}
}
}
Output:
Enter the number ar[0]:15 Enter the number ar[1]:25 Enter the number ar[2]:45 Enter the number ar[3]:36 Enter the number ar[4]:12 Enter the number ar[5]:32 Enter the number ar[6]:47 Enter the number ar[7]:65 Enter the number ar[8]:69 Enter the number ar[9]:58 Enter number to be search:32 Position=6java java tutorials learn java study java