Linear Search in Array

This program performs linear search to find an element in an array.

Problem Statement

Write a Java program to search for a given element in an integer array using linear search.

Source Code

1 public class LinearSearch {
2 public static void main(String[] args) {
3 int[] arr = {10, 25, 30, 45, 50};
4 int key = 30;
5 boolean found = false;
6 for(int i=0; i<arr.length; i++) {
7 if(arr[i] == key) {
8 System.out.println("Element found at index: " + i);
9 found = true;
10 break;
11 }
12 }
13 if(!found) System.out.println("Element not found");
14 }
15 }

Program Output

Element found at index: 2

Explanation

Array arr initialized with integers. - Variable key stores the element to be searched. - For loop iterates through each element. - If element matches key, index is printed and loop breaks. - If not found, message is displayed. - Demonstrates linear search algorithm. Conclusion: Shows how linear search can be implemented in arrays.

Quick Links to Explore