Dharanyadevi blogspot subsume with E-books, Notes, Lab Manual, Question Banks, Interview Tips, Viva Questions, Basics and Interview Questions for engineering students. For Any Help Contact dharanyadevi@gmail.com

SEARCH

Image

Monday, April 23, 2012

Linear Search in C and Linear Search Using Functions

Linear Search in C

Linear search in c programming: The following code implements linear search ( Searching algorithm ) which is used to find whether a given number is present in an array and if it is present then at what location it occurs. It is also known as sequential search. It is very simple and works as follows: We keep on comparing each element with the element to search until the desired element is found or list ends.

#include
 main()
{
   int array[100], search, c, number;
    printf("Enter the number of elements in array\n");
   scanf("%d",&number);
    printf("Enter %d numbers\n", number);
    for ( c = 0 ; c < number ; c++ )
      scanf("%d",&array[c]);
    printf("Enter the number to search\n");
   scanf("%d",&search);
    for ( c = 0 ; c < number ; c++ )
   {
      if ( array[c] == search )     /* if required element found */
      {
         printf("%d is present at location %d.\n", search, c+1);
                break;
      }
   }
   if ( c == number )
      printf("%d is not present in array.\n", search);     
    return 0;
}
 

C Program for Linear Search using Function

#include
 int linear_search(int*, int, int);
 main()
{
   int array[100], search, c, n, position;
    printf("Enter the number of elements in array\n");
   scanf("%d",&n);
    printf("Enter %d numbers\n", n);
 
   for ( c = 0 ; c < n ; c++ )
      scanf("%d",&array[c]);
    printf("Enter the number to search\n");
   scanf("%d",&search);
    position = linear_search(array, n, search);
    if ( position == -1 )
      printf("%d is not present in array.\n", search);
   else
      printf("%d is present at location %d.\n", search, position+1);
    return 0;
} 
 
int linear_search(int *pointer, int n, int find)
{
   int c;
    for ( c = 0 ; c < n ; c++ )
   {
      if ( *(pointer+c) == find )
         return c;
   }
    return -1;
}

2 comments:

  1. I know this website provides quality dependent posts and other material,
    is there any other site which provides these stuff in quality?



    Visit my web-site: cuban coffee

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Refer this site 2 ur frndz