Here is a simple Java program to perform Linear Search on an array:
β Linear Search Example in
import java.util.Scanner;
public class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input array size
System.out.print(“Enter the number of elements: “);
int n = sc.nextInt();
int[] arr = new int[n];
// Input array elements
System.out.println(“Enter the elements:”);
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Input the element to search
System.out.print(“Enter the element to search: “);
int key = sc.nextInt();
// Linear search
boolean found = false;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
System.out.println(“Element found at index ” + i);
found = true;
break;
}
}
if (!found) {
System.out.println(“Element not found in the array.”);
}
sc.close();
π’ Sample Output
Enter the number of elements: 5
Enter the elements:
10
20
30
40
50
Enter the element to search: 30
Element found at index 2
}
}