-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinearSearch.java
52 lines (46 loc) · 1.41 KB
/
linearSearch.java
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
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.Scanner;
public class linearSearch
{
public static void main(String args[])
{
//Declaration
Scanner sc = new Scanner(System.in);
int n, key, position = 0 , index = 0;
int a[];
boolean flag = false;
//Prompt and Accept the number of students
System.out.println("Please enter the number of students: ");
n = sc.nextInt();
//Create a new Array
a = new int[n];
//Reading the Array Elements from the user
System.out.println("Please enter the number(s): ");
for(int i = 0 ; i < a.length ; i++)
{
a[i] = sc.nextInt();
}
//accepting the value to be searched from the user
System.out.println("Please enter the number to be searched ");
key = sc.nextInt();
//linear Search
for(int i = 0 ; i < a.length ; i++)
{
if( key == a[i])
{
flag = true;
index = i;
position = i+1;
break;
}
}
//dislpaying the result after searching
if(flag == true)
{
System.out.println(key + " was found at position " + position + ", index: " + index );
}
else if ( flag == false)
{
System.out.println(key + " was not found");
}
}
}