pgrm_006.cpp (1200B)
1 /* Write a program in cpp to implement linear search using private instance variable and public member methods. */ 2 3 #include <iostream> 4 using namespace std; 5 6 class linearSearch { 7 private: 8 int *arr; 9 int n; 10 11 public: 12 linearSearch(int size) { 13 n = size; 14 arr = new int[n]; 15 } 16 17 void getData() { 18 for (int i = 0; i < n; i++) { 19 cout << "Enter element " << i + 1 << ": "; 20 cin >> arr[i]; 21 } 22 } 23 24 void lsearch(int key) { 25 int found = 0; 26 for (int i = 0; i < n; i++) { 27 if (arr[i] == key) { 28 cout << "Element's pos: " << (i + 1) << endl; 29 found = 1; 30 break; 31 } 32 } 33 if (found == 0) { 34 cout << "Element not found" << endl; 35 } 36 } 37 38 ~linearSearch() { 39 delete[] arr; 40 } 41 }; 42 43 int main() { 44 int n, key; 45 cout << "Enter the number: "; 46 cin >> n; 47 linearSearch obj(n); 48 obj.getData(); 49 cout << "Enter element to search: "; 50 cin >> key; 51 obj.lsearch(key); 52 return 0; 53 }