Skip to content

Commit 0165a42

Browse files
committed
feat: Search for an element in an array using linear search
🧠 Logic: - Takes the size of the array and its elements from the user. - Prints all array elements. - Asks the user for an element to search (`s`) in the array. - Uses a linear search (`for` loop) to check each element: - If match is found, sets `x = 1` and stores the index in `pos`, then breaks the loop. - After search: - If `x == 0`, element was not found. - If `x == 1`, displays the index where the element was found. Signed-off-by: Somesh diwan <[email protected]>
1 parent eb48782 commit 0165a42

File tree

1 file changed

+4
-1
lines changed

1 file changed

+4
-1
lines changed

Section8LoopAB/Loop 2.O/src/LoopsPractice.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,20 @@
33
class LoopsPractice {
44
public static void main(String[] args) {
55
Scanner sc = new Scanner(System.in);
6+
67
int n, s, x = 0, pos = 0;
8+
79
System.out.println("Enter size of an array");
810
n = sc.nextInt();
11+
912
int[] A = new int[n];
1013
System.out.println("Enter Array elements:");
1114

1215
for (int i = 0; i < A.length; i++) {
1316
A[i] = sc.nextInt();
1417
}
15-
System.out.println("Array elements are: ");
1618

19+
System.out.println("Array elements are: ");
1720
for (int i = 0; i < A.length; i++) {
1821
System.out.println(A[i]);
1922
}

0 commit comments

Comments
 (0)