pgrm_012.cpp
Problem Statement
pgrm_012.cpp
Linear search in cpp
Source Code
cpp
#include<iostream>
using namespace std;
class LinearSearch {
private:
int arr[10];
int n;
public:
LinearSearch() {n = 0;}
void getData() {
cout << "Enter number of elements: ";
cin >> n;
cout << "Enter " << n << " elements: ";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
}
void Lsearch(int &key, int &position) {
position = -1;
for(int i = 0; i < n; i++) {
if(arr[i] == key) {
position = i + 1;
}
}
}
};
int main() {
LinearSearch obj;
int key, pos;
obj.getData();
cout << "Enter the element to search: ";
cin >> key;
obj.Lsearch(key, pos);
if(pos != -1) {
cout << "Element found at position " << pos << endl;
}
else {
cout << "Element not found." << endl;
}
return 0;
}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
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
● Author - Amit Dutta · Updated - 10 Jul 2026