Wednesday, November 30, 2016

C Program for Linear Search

      In Linear search element are examined sequentially starting from the first element. The process of searching terminates when the list is exhausted or a comparison results in success.

      Algorithm for searching an element 'key' in an array 'a[]' having N element. The search algorithm start, comparison between first element of 'a[]' and 'key'. As long as comparison does not result in success, the algorithm proceed to compare the next element of 'a[]' with 'key'. The process terminates when the first is exhausted or the element is found.

      Ex.
Algorithm:-
  1. Start
  2. Initialize Variables to required and Initialize array of size 'N' 
  3. Read array of integer number which size 'N'
  4. Assign i=0 and check unit i<N
  5. Compare for (a[i]==28) if number is found, go to step 7, make flag=1
  6. If number not found, Increment i and go to step 5
  7. If flag=1, than print number is found. If flag=0, than print number is not found
  8. Stop 
Program:-

#include<stdio.h>
#include<conio.h>
void main()
{
                int i,key,a[12],n,flag=0;
                clrscr();
                printf("\n how many elements in array=");
                scanf("%d",&n);
                printf("\n enter array element\n");
                for(i=0;i<n;i++)
                {
                                scanf("%d",&a[i]);
                }
                printf("\n enter the element to be searched=");
                scanf("%d",&key);
                for(i=0;i<n;i++)
                {
                                if(a[i]==key)
                                {
                                                flag=1;
                                                break;
                                }
                }
                if(flag==0)
                printf("\n key is not found");
                else
                printf("\n key i.e. number is %d found at pos=%d",key,i+1);
                getch();
}



Output:-

Please comment and give Suggestion on this post, if you want any other program or help then type in comment or contact me, and give feedback for this blogs.

No comments:

Post a Comment

Acer Nitro 5 Ryzen 7 4800H - Blender Open Data Benchmark | Blender BMW Benchmark

Hello friends in this video I have perform benchmark of Acer Nitro 5 Ryzen 7 4800H laptop using Blender Open data Benchmark tool. In this to...