Friday, February 20, 2015

Implementation of Linear Search

AIM:
          To write a C program to implement Linear Search

ALGORITHM:
            Step 1: Start the program.
Step 2: Get the total number of elements to be entered n
Step 3: Setup a for loop c=0 ;until c<n; increment i
Step 4: Read the numbers into the array
Step 5: Read which element to be searched in search
Step 6: Setup a for loop c=0 ;until c<n; increment i
Step 7: Evaluate if(search==array[i])
            If it is found then print the number and its position
Step 8: Stop the program.

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





OUTPUT
Enter the number of elements in array
5
Enter the numbers
5
6
4
2
9
Enter the number to search
4
4 is present at location 3


RESULT: Thus a C program is written to implement linear search and executed
                   successfully




No comments:

Post a Comment