Showing posts with label linear search. Show all posts
Showing posts with label linear search. Show all posts

Tuesday, 19 November 2013

linear search without recursion

Linear Search Without Recursion Using C Program

Program:


#include<stdio.h>

void main()

{

    int a[50],n,f,key,i;

    clrscr();

    printf("enter no of elements to be entered");

    scanf("%d",&n);

    printf("enter elements ");

    for(i=1;i<=n;i++)

        scanf("%d",&a[i]);

    printf("enter the key value to find");

    scanf("%d",&key);

    f=lsearch(a,n,key);

    if(f==0)

       printf("the key not found");

    else

       printf("the %d is found at %d",key,f);

    getch();

}

int lsearch(int a[],int n,int key)

{

    int i;

    for(i=1;i<=n;i++)

    {

        if(a[i]==key)

        return i;

    }

    return 0;

}

Output:


Saturday, 16 November 2013

Linear search

Linear Search With Recursion Using C program


Program:

#include<stdio.h>

void main()

{

   int n,a[20],i,j,key;

   clrscr();

   printf("enter no of elements to be entered");

   scanf("%d",&n);

   printf("enter elements");

   for(i=1;i<=n;i++)

      scanf("%d",&a[i]);

   printf("enter the key to search");

   scanf("%d",&key);

   j=rlsearch(a,1,n,key);

   if(j==0)

       printf("the element is not found");

   else

       printf("the element found at %d",j);

   getch();

}

int rlsearch(int a[],int i,int n,int key)

{

   if(i>n)

      return 0;

   if(a[i]==key)

      return i;

   else 

      return rlsearch(a,i+1,n,key);

}

Output: