write a program in java to accept 10 numbers in single dimensional array .enter a no and search whether the no is present or not using linear search
Answers
class Search
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
int num[] = new int[10];
int ns, i, flag = 0;
System.out.println ("Enter the 10 No's: ");
for (i = 0; i < 10; i++)
{
num[i] = sc.nextInt();
}
System.out.print(" Enter the number to be searched: ");
ns = sc.nextInt();
for (i = 0; i < 10; i++)
{
if (ns == num[i])
{
flag = 1;
break;
}
}
if (flag == 1)
System.out.println(" Search successful!");
else
System.out.println ("Search unsuccessful!");
}
}
Thanks..please follow to get more answers!
Answer:
import java.util.*;
class linear_search
{
public void main()
{
Scanner sc=new Scanner(System.in);
int a[]=new int[10];
System.out.println("Enter the array elements");
for(int i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
int i;
System.out.println("Enter the elements that need to be searched");
int element=sc.nextInt();
for(i=0;i<10;i++)
{
if(element==a[i])
{
System.out.println("Search succesful");
System.out.println("Present at:"+(i+1));
break;
}
}
if(i==n)
{
System.out.println("Search unsuccessful");
}
}
}
Explanation:
We take 10 elements as input by using Scanner class and storing the inputs in an array .
Linear searches compares the element to be searched with all the elements all the array .