Linear Search in Java


Q. Write a Java program for Linear Search

 import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input array size
        System.out.print("Enter the number of elements: ");
        int n = scanner.nextInt();

        int[] arr = new int[n];

        // Input array elements
        System.out.println("Enter " + n + " integers:");
        for (int i = 0; i < n; i++) {
            arr[i] = scanner.nextInt();
        }

        // Input the target element to search
        System.out.print("Enter the element to search: ");
        int target = scanner.nextInt();

        // Perform linear search
        boolean found = false;
        int position = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] == target) {
                found = true;
                position = i;
                break;
            }
        }

        // Display result
        if (found) {
            System.out.println("Element found at index: " + position);
        } else {
            System.out.println("Element not found in the array.");
        }

        scanner.close();
    }
}

Q. Write an algorithm for Linear Search

1. Start
2. Read n (number of elements)
3. Read n elements into array arr[]
4. Read the element to search (target)
5. Initialize found = false
6. Loop from i = 0 to n - 1:
    a. If arr[i] == target, then
        Set found = true
        Print the index i
        Break the loop
7. If found == false, print "Element not found"
8. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.