Linear search in 1d array with OOPS concept

PHOTO EMBED

Tue Apr 11 2023 03:50:02 GMT+0000 (Coordinated Universal Time)

Saved by @ronin_78 #c++

#include <iostream>
using namespace std;

class linearsearch {
    private:
        int a[100], n, x;
        
    public:
        int search(int arr[], int size, int key) {
            n = size;
            x = key;
            
            for (int i=0; i < n; i++) {
            a[i] = arr[i];
            }   
        
            for (int i = 0; i < size; i++) {
                if (arr[i] == key) {
                    return i;
                }
            }
            return -1;
        }
};

int main() {
    int size, x;
    
    cout << "Enter the size of the 1-d array: ";
    cin >> size;
    int arr[size];
    
    cout << "Enter all the elements separated with spaces\n";
    for(int i=0; i<size; i++){
        cin>>arr[i];
    }
    
    cout <<"Enter the element to do linear search: ";
    cin >>x;
    
    linearsearch ls;
    int index = ls.search(arr, size, x);

    if (index == -1) {
        cout << x <<" not found" << endl;
    } else {
        cout << x <<" found at index " << index <<" (starts from 0)." <<endl;
    }

    return 0;
}
content_copyCOPY