bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_2 / eduincs / pgrm_023.cpp

pgrm_023.cpp (1059B)


      1 /* WAP to implement linear search template class and template function */
      2 
      3 #include<iostream>
      4 using namespace std;
      5 
      6 template <class T>
      7 class LinearSearch {
      8 private:
      9     T *arr;
     10     int size;
     11     T key;
     12 
     13 public:
     14     LinearSearch(int n) {
     15         size = n;
     16         arr = new T[size];
     17 
     18         cout << "Array Size: " << size << endl;
     19 
     20         cout << "Enter elements: ";
     21         for(int i = 0; i < size; i++) {
     22             cin >> arr[i];
     23         }
     24 
     25         cout << "Enter key: ";
     26         cin >> key;
     27     }
     28     
     29     int search() {
     30         for(int i = 0; i < size; i++) {
     31             if(arr[i] == key)
     32                 return i;
     33         }
     34         return -1;
     35     }
     36 };
     37 
     38 int main() {
     39 
     40     LinearSearch<int> obj(5);
     41     int index = obj.search();
     42     if(index != -1)
     43         cout << "Key found at: " << index << endl;
     44     else
     45         cout << "Key not found!" << endl;
     46 
     47     LinearSearch<double> obj2(5);
     48     index = obj2.search();
     49     if(index != -1)
     50         cout << "Key found at: " << index << endl;
     51     else
     52         cout << "Key not found!" << endl;
     53 
     54     return 0;
     55 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror