Wednesday, 29 October 2014

linear search

#include<stdio.h>
int main()
{
    int list[100],n,i,x,p,found=0;
    printf("\n Enter the size of the list:");    //entering the size of the array
    scanf("%d",&n);
    printf("\n Enter the elements:\n");        //entering the elements of the array
    for(i=0;i<n;i++)
    {
        scanf("%d",&list[i]);
    }
    p=0;
    printf("\n Enter the element to be searched:");        //entering the KEY element to be searched
    scanf("%d",&x);
    for(i=0;i<n;i++)
    {
        if(list[i]==x)        //if KEY element is found then
        {                   
            p=i;        //store the index value of the array in another variable
            found=1;           
        }
    }
        if(found>0)
        {
            printf("\n The position of element %d is %d",x,p+1);        //print the KEY element along with its position in the array
        }
        else
        {
            printf("\n Try Again");       
        }
    return 0;        //end of program
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.