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