pgrm_006.cpp
Problem Statement
pgrm_006.cpp
Write a program in cpp to implement linear search using private instance variable and public member methods.
Source Code
cpp
#include <iostream>
using namespace std;
class linearSearch {
private:
int *arr;
int n;
public:
linearSearch(int size) {
n = size;
arr = new int[n];
}
void getData() {
for (int i = 0; i < n; i++) {
cout << "Enter element " << i + 1 << ": ";
cin >> arr[i];
}
}
void lsearch(int key) {
int found = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
cout << "Element's pos: " << (i + 1) << endl;
found = 1;
break;
}
}
if (found == 0) {
cout << "Element not found" << endl;
}
}
~linearSearch() {
delete[] arr;
}
};
int main() {
int n, key;
cout << "Enter the number: ";
cin >> n;
linearSearch obj(n);
obj.getData();
cout << "Enter element to search: ";
cin >> key;
obj.lsearch(key);
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
44
45
46
47
48
49
50
51
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
● Author - Amit Dutta · Updated - 06 Jul 2026