Structure of the Problem Requirements
In this Problem we will discuss about linear search in Java. Although linear search is very simple and easy technique to search from an array. In this problem first we add elements and then save in a array and then apply linear search for searching an element from an array.Here is the source code of this problem which help you in better understanding .
SOURCE CODE
import java.util.Scanner;
classLinearSearch
{
public static void main(String args[])
{
int arr;
int search;
int number;
int array[];
Scanner in = new Scanner(System.in);
System.out.println("How Many Elements :");
number = in.nextInt();
array = new int[number+1];
for (arr = 1; arr < number+1 ; arr++)
{
System.out.println("Enter " + arr + "");
array[arr] = in.nextInt();
}
System.out.println("Enter value to find");
search = in.nextInt();
for (arr = 0; arr < number; arr++)
{
if (array[arr] == search)
{
System.out.println(search + " Present at Index " + (arr) + ".");
break;
}
}
if (arr == number)
System.out.println(search + "Invalid Input ! ");
}
}
OUTPUT OF THE PROGRAM
Linear Search in Java |
Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.
This comment has been removed by the author.
ReplyDeleteI got answer of my interview question.
ReplyDeleteThanks a lot for clearing my idea.