Computer Applications

Define a class to accept 10 integers in an array, search for the given value using the Linear Search technique and print appropriate messages.

Java

Java Arrays

6 Likes

Answer

import java.util.Scanner;
public class LinearSearchArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[10];

        System.out.println("Enter 10 integers:");
        for (int i = 0; i < 10; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.print("Enter the value to search: ");
        int key = sc.nextInt();
        int i = 0;

        for (i = 0; i < 10; i++) {
            if (arr[i] == key) {
                break;
            }
        }
        
        if (i < 10)
            System.out.println("Value found at position: " + (i + 1));
        else
            System.out.println("Value not found in the array");
    }
}

Output

Answered By

2 Likes


Related Questions