Linear Search
Linear Search
Linear Search
The input is
an array of length n, according to the user’s choice and the key element to be
found. Print the index values of all the occurrences of the key value.
(2 marks)
Input:
Enter the length of the array
5
Enter the element of the array
1 6 3 7 7
Enter the key value
7
Output:
index - 3 4
SOLUTION:
INPUT:
import java.util.*;
public class LinearSearch {
static void linearsearch()
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the length of the array");
int a= sc.nextInt();
int[] arr = new int[a];
System.out.println("Enter the elements of the array");
for(int i=0; i<a; i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Enter the key value");
int num=sc.nextInt();
System.out.print("index -");
for(int i=0;i<a;i++)
{
if (arr[i]== num)
System.out.print(" "+ i );
}
}
public static void main(String[] args) {
linearsearch();
}
}