/* Demonstration of linear search algorithm used to find
   a student's grade from a set of grade records.  The key
   for the search is the student's I.D. number.
*/

#include<stdio.h>
#include<stdlib.h>

#define MAXSTUDENTS 50     /*  Constant  */

/*  linear Function Declaration  */
int linear(long int id[], long int key, int n)
{
/*   Simple linear search - check all the elements of the
     array for a match starting at zero until a match is found.
     On average, the function will make n/2 comparisons.
     If no match is found, a not-found flag is returned, otherwise
     the function returns the correct subscript for the student record
*/
  int i, flag;
  flag = -1;
  for( i=0; i<n; i++){
    if( id[i] == key ){
      flag = i;
      break;
    }
  }
  return(flag);
}

main()
{
  /*  Declaration Statements  */
  char names[MAXSTUDENTS][25];
  int i, n, flag, cont, yes_no;
  long int id[MAXSTUDENTS], key;

  /*  Enter data  */
  do{
     printf("How many students? (<%4d)",MAXSTUDENTS);
     scanf("%d",&n);
     }while( n>MAXSTUDENTS );

  printf("Enter students' names and grades\n");
  printf("in this format ->Name:Doe,John[ENTER] (no spaces)\n");
  printf("               ->ID #:9421234[ENTER]\n");
  for( i=0; i<n; i++){
     printf("Student #%d:\n",i+1);
     printf("Name: ");
     scanf("%s",names[i]);
     printf("ID #: ");
     scanf("%ld",&id[i]);
     }

  printf("\n\n\nDemonstration of linear search\n\n");

 do{   /* Keep on looking up names until user wants to quit */

  printf("Enter search key (ID#)\n");
  scanf("%ld",&key);

  printf("\n  **SEARCHING**\n");

  flag = linear(id, key, n);

 /* flag will equal -1 if no match was found, or the correct
    array subscript for the student  */

  cont = 0;
  if(flag == -1){
    printf("Search key not found - check ID #\nTry again (y/n)? ");
    scanf("%d",&yes_no);
    }
  else {
    printf("  **FOUND**\n");
    printf("Name:%s  ID #:%ld\n\n", names[flag], id[flag]);
    printf("Look up another student (0 for no, 1 for yes)? ");
    scanf("%d",&yes_no);
    }
 }while(yes_no == 1);

}
/*  End of main program linear.c  */