Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Wednesday, 27 March 2019

Sequential Search Algorithm

ALGORITHM SequentialSearch(A[0..n 1], K)

//Searches for a given value in a given array by 

//sequential search

//Input: An arrayA[0..n 1] and a search key K

//Output: The index of the first element in that matches K

// or -1 if there are no matching elements

← 0

while i < n and A[ido

← 1

if i < n return i

else return -1


C program:


#include <stdio.h> int main()

{

  int array[100], search, c, n; 


  printf("Enter 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 a number to search\n");

  scanf("%d", &search); 

  for (c = 0; c < n; c++)  {

    if (array[c] == search)    /* If required element is found */    { 

     printf("%d is present at location %d.\n", search, c+1);

      break;    }

  }

  if (c == n)

    printf("%d isn't present in the array.\n", search);   return 0;

}



Output:

Enter number of elements in array

5

Enter 5 integer(s)

1

3

6

2

4

Enter a number to search

3

3 is present at location 2.

0 comments:

Post a Comment