Pls Write an Array proram In linear search with taking inputs from the user
Answers
Answer:
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int n, item;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements:");
n = sc.nextInt();
int[] array = new int[n];
System.out.println("Enter " + n + " integers");
for (int i= 0; i< n; i++)
array[i] = sc.nextInt();
System.out.println("Enter the search value:");
item = sc.nextInt();
for (int i = 0; i < n; i++)
{
if (array[i] == item)
{
System.out.println(item+" is present at location "+(i+1));
break;
}
}
if (i== num)
System.out.println(item + " doesn't exist in array.");
}
}
Explanation:
Logic is very simple:
Start from the leftmost element of array[] and one by one compare x with each element of array[]
If x matches with an element, print the index and break the loop
If x doesn’t match with any of elements, i equals value of number of elements then it prints the message it doen't exist in array