In this post we will discuss on a basic searching technique called as linear search . It searches an element (generally called a key ) from an array. Unlike binary search , the array need not to be sorted. |
PROGRAM :
OUTPUT :
#include <iostream> using namespace std; int main() { int array[100], key, i, n; cout << "How many elements? \t"; cin >> n; for (i = 0; i < n; i++) { cout << "Enter number "<< i+1 << ": \t"; cin >> array[i]; } cout << "\n\nEnter the number to search: \t"; cin >> key; for (i = 0; i < n; i++) { if (array[i] == key) { cout << "\n\n" << key <<" is present at position" << i+1 << endl; break; } } if (i == n) cout << "\n\n" << key <<" is not present in array.\n"; return 0; }
OUTPUT :
Linear Search technique |