Saturday, 3 January 2015

C Program for implementing Linear Search


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 <stdio.h>
#include <stdlib.h>
int main()
{
    int array[100], key, i, n;
    
    printf("How many elements? \t");
    scanf("%d",&n);   
    
    for (i = 0; i < n; i++){
        printf("Enter number %d :\t", i+1);
        scanf("%d", &array[i]);
    }
        
    printf("\n\nEnter the number to search:\t");
    scanf("%d", &key);
    
    for (i = 0; i < n; i++)
    {
        if (array[i] == key)
        {
            printf("\n\n%d is present at position %d.\n", key, i+1);
            break;
        }
    }
    if (i == n)
        printf("\n\n%d is not present in array.\n", key);
    return 0;
}

OUTPUT :