Write a program to input a single dimensional array of 20 integers and search for an integer
value input by the user in an array by using Linear Search Technique. If found display
“Search Successful” otherwise display “Search Unsuccessful”.
Answers
Solution:
This is written in Java.
import java.util.*;
public class LinearSearch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter 20 elements.");
int a[]=new int[20];
for(int i=0;i<20;i++){
System.out.print(">> ");
a[i]=sc.nextInt();
}
System.out.print("Enter the number you are searching for: ");
int x=sc.nextInt();
sc.close();
boolean found=false;
for(int y:a){
if(y==x) {
found=true;
break;
}
}
if(found)
System.out.println("Search Successful. Element found.");
else
System.out.println("Search Unsuccessful. Element not found.");
}
}
We assume that the element is not in the list (found = false). Now, we will loop through array elements and check if the element is present or not. If true, assign found = true and break the loop.
At last, check if found == true. If true, "search successful" or else, "search unsuccessful".
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a[]=new int[20];
int ns,f=0,pos=0;
System.out.println("Enter the elements of the array:");
for(int i=0;i<a.length;i++)
{
a[i]=in.nextInt();
}
System.out.println("Given Array:"+Arrays.toString(a));
System.out.println("Enter the element to be searched:");
ns=in.nextInt();
for(int i=0;i<a.length;i++)
{
if(a[i]==ns)
{
f=1;
pos=i;
break;
}
}
if(f==1)
System.out.println("Searched Successful the number is found in the array at position "+(pos+1));
else
System.out.println("Searched Unsuccessful the number is not found in the array");
}
}
Refer to the attachments:-
- The output of the array of the element i have given the element, that is present there and the element that is absent there The first photo is the 1st half photo and the 2nd photo is the second half photo. The third photo(2nd output) is the 3rd half photo and 4th photo is the half photo for the second one.
- I have also give the position +1 as the index of the array starts with 0 so pos+1.
- If element is not present it displays search unsuccessful.
Logic:-
- In linear search we can search the element in a unsorted array.
- If element is found in the array f=1 and the index position is i and the loop is terminated so as to save time.