Skip to content

Commit 8398fa2

Browse files
committed
feat: Search for an element in an array using linear search
🧠 Logic: - Initialize a fixed array of integers. - Read a key from user input. - Traverse the array using a loop and compare each element with the key. - If found, print the index and exit the program immediately. - If loop completes without finding the key, print "Not Found". Signed-off-by: Somesh diwan <[email protected]>
1 parent e093752 commit 8398fa2

File tree

1 file changed

+5
-7
lines changed

1 file changed

+5
-7
lines changed
Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import java.util.Scanner;
22

33
public class SearchAnElementArray {
4-
public static void main(String[] args)
5-
{
4+
public static void main(String[] args) {
65
Scanner sc = new Scanner(System.in);
76
int A[]={3,9,7,8,12,6,15,5,4,10};
87

@@ -11,14 +10,13 @@ public static void main(String[] args)
1110
System.out.println("Enter a key: ");
1211

1312
key= sc.nextInt();
14-
for(int i=0; i<A.length; i++)
15-
{
13+
for(int i=0; i<A.length; i++) {
1614
if (key==A[i])
1715
{
18-
System.out.println("Element Found At : "+i);
19-
System.exit(0);
16+
System.out.println("Element Found At : "+i);
17+
System.exit(0);
2018
}
2119
}
2220
System.out.println("Not Found");
2321
}
24-
}
22+
}

0 commit comments

Comments
 (0)