-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathLinearSearchExample.java
More file actions
40 lines (33 loc) · 1021 Bytes
/
LinearSearchExample.java
File metadata and controls
40 lines (33 loc) · 1021 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
// To capture user input
Scanner input = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = input.nextInt();
// Creating array to store the all the numbers
array = new int[num];
System.out.printf("Enter %d integers\n", num);
// Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = input.nextInt();
System.out.println("Enter the search value:");
item = input.nextInt();
for (counter = 0; counter < num; counter++) {
if (array[counter] == item) {
System.out.printf("%d is present at location %d.\n", item, (counter + 1));
/*
* Item is found so to stop the search and to come out of the loop use break
* statement.
*/
break;
}
}
if (counter == num)
System.out.println(item + " doesn't exist in array.");
input.close();
}
}