-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinearSearch.cpp
61 lines (48 loc) · 1.37 KB
/
LinearSearch.cpp
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
53
54
55
56
57
58
59
60
61
/* PROGRAM FOR LINEAR SEARCH ALGORITHM */
#include <iostream>
using namespace std;
void LinearSearch(int size, int array[], int key) {
// if element found we will set this varialbe as true
bool found = false;
// this will record the index of array where key is found
int index;
// linearSearch algorithm
for (int j = 0; j < size; j++) {
if (array[j] == key) {
// if found set index current value of loop iteration
found = true;
index = j;
}
}
if (found) {
cout << "Element found at index: " << index << endl;
} else {
cout << "Element not found in array." << endl;
}
}
int main() {
// array of size 20
int array[20];
/* initialising array with custom size
which user will enter */
int size;
// element to search
int key;
cout << "LINEAR SEARCH" << endl;
// enter the size of array
cout << "Enter the size of array: ";
cin >> size;
array[size];
// enter the array elements
cout << "Enter the array elements" << endl;
for (int i = 0; i < size; i++) {
cout << " Enter element at " << i << "th index: ";
cin >> array[i];
}
// enter element to search
cout << "\nEnter element to search: ";
cin >> key;
// calling function linearSearch()
LinearSearch(size, array, key);
return 0;
}