/*
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 */
/*
Input :
8
Milo,Bloom 9611684
Cat,theBill 9613986
Dallas,Steven 9412978
Cutter,John 9613693
Jones,Oliver 9515010
Binkley,Mike 9510633
Opus,Holland 9513221
Dummy,One 0000000
Output :
How many students? (< 50)Enter students' names and grades
in this format ->Name:Doe,John[ENTER] (no spaces)
->ID #:9421234[ENTER]
Student #1:
Name:Milo,Bloom
ID #:9611684
Student #2:
Name:Cat,theBill
ID #:9613986
Student #3:
Name:Dallas,Steven
ID #:9412978
Student #4:
Name:Cutter,John
ID #:9613693
Student #5:
Name:Jones,Oliver
ID #:9515010
Student #6:
Name:Binkley,Mike
ID #:9510633
Student #7:
Name:Opus,Holland
ID #:9513221
Student #8:
Name:Dummy,One
ID #:0000000
Demonstration of linear search
Enter search key (ID#)
9611684
**SEARCHING**
**FOUND**
Name:Milo,Bloom ID #:9611684
Look up another student (0 for no, 1
for yes)?0
*/