Find a Data Element Using a Linear Search - C Data Structure

C examples for Data Structure:Search

Description

Find a Data Element Using a Linear Search

Demo Code

#include <stdio.h>

int myArray[50];/* w  w w . ja va  2  s .c om*/
int count = 0;

int searchData(int intData)
{
  int intCompare = 0;
  int intNum = -1;
  int i;
  for(i = 0; i < count; i++) {
    intCompare++;
    if(intData == myArray[i]){
      intNum = i;
      break;
    }
  }
  printf("Total Number of Comparisons Made Are: %d", intCompare);
  return intNum;
}

int main()
{
  int intPosition, intData, i;
  printf("Enter the number of data elements N (2 <= N <= 50): ");
  scanf("%d", &count);
  printf("Enter the %d integers I (0 <= I <= 30000) ", count);
  printf("separated by white spaces: \n");
  for (i=0; i < count; i++)
    scanf("%d", &myArray[i]);
  fflush(stdin);
  printf("Enter the Data Element D to be Searched (0 <= D <= 30000): ");
  scanf("%d", &intData);
  intPosition = searchData(intData);
  if(intPosition != -1) {
    printf("\nData Element Found at Position ");
    printf("or Location: %d\n", (intPosition + 1));
  }
  else
     printf("\nData Element Not Found.\n");
  printf("\nThank you.\n");
}

Result


Related Tutorials