Friday, 27 March 2015

Cpp Program for implementing Linear Search technique.



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.
This Linear Search technique generally compares each and every element with the key , if both matches , the algorithm returns that element is found and its position.




PROGRAM :
#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


Download Code