#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; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter