File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ //Performing Linear search of any number entered by user in an Array
2+ import java .util .Scanner ;
3+ public class linearSearch {
4+
5+ public static void main (String [] args ) {
6+ Scanner reader = new Scanner (System .in );
7+ int num [];
8+ int i ;
9+ int search ;
10+ //(optional) count is required to print how many times an element occurs in an array
11+ int count =0 ;
12+
13+ // Declaring array of n numbers
14+ System .out .println ("enter number of elements in array :" );
15+ int n = reader .nextInt ();
16+ num = new int [n ];
17+
18+ //Taking input for elements of array from user
19+ System .out .println ("Enter elements in array: " );
20+ for (i =0 ;i <n ;i ++)
21+ {
22+ num [i ] = reader .nextInt ();
23+
24+ }
25+
26+ //searching given element in array
27+ System .out .println ("enter element to be searched " );
28+ search = reader .nextInt ();
29+ for (i =0 ;i <n ;i ++)
30+ {
31+ if (num [i ]==search )
32+ {
33+ System .out .println (search +" is found at index " +(i +1 ));
34+
35+ count ++;
36+ }
37+ }
38+
39+ //if given element is not present in array
40+ if (count ==0 )
41+ {
42+ System .out .println ("element not found!" );
43+ }
44+ //optional: to print how many times the searched number occurs in the array
45+ else {
46+ System .out .println (search +" is occuring " +count +" times" );
47+ }
48+
49+
50+ }
51+ }
52+
You can’t perform that action at this time.
0 commit comments