Sunday 7 April 2013

lenear seach in C


#include <stdio.h>

int 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;
}
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

2 comments:

  1. A shorter/cleaner way

    for (c=0; c<number && array[c]!=search; c++)
    ;

    if (c==number)
    printf ("%d not present in array\n", search);
    else
    printf ("%d found at position %d\n", c); // Starting at index zero.

    ReplyDelete
  2. A better way to iterate over arrays is not by using a num/variable (what in case the user enters 100 when the array is only 50 elements long?)

    Rather use one of the methods documented here: http://lelanthran.com/deranged/?p=182

    ReplyDelete