pgrm_012.cpp (913B)
1 /* Linear search in cpp */ 2 3 #include<iostream> 4 using namespace std; 5 class LinearSearch { 6 private: 7 int arr[10]; 8 int n; 9 public: 10 LinearSearch() {n = 0;} 11 12 void getData() { 13 cout << "Enter number of elements: "; 14 cin >> n; 15 cout << "Enter " << n << " elements: "; 16 for(int i = 0; i < n; i++) { 17 cin >> arr[i]; 18 } 19 } 20 21 void Lsearch(int &key, int &position) { 22 position = -1; 23 for(int i = 0; i < n; i++) { 24 if(arr[i] == key) { 25 position = i + 1; 26 } 27 } 28 } 29 }; 30 31 int main() { 32 LinearSearch obj; 33 int key, pos; 34 obj.getData(); 35 cout << "Enter the element to search: "; 36 cin >> key; 37 obj.Lsearch(key, pos); 38 if(pos != -1) { 39 cout << "Element found at position " << pos << endl; 40 } 41 else { 42 cout << "Element not found." << endl; 43 } 44 return 0; 45 }