Reputation: 31
i see plenty of examples on how to search arrays to find a specific instance what i want to do is find all the instances and print them for example i have this struct
struct BookInfo
{
char title[50];
int numAuthors;
char authors[50][50];
int year;
int checkedout;
};
struct BookInfo library[500];
and i have a function to search within the years but it only gives me the first instance it finds how do i get it to give me bot instances??? heres the function
int yearsearch()
{
int target, i, l, r, mid;
l = 0;
r = 14-1;
printf("type a year to search for book");
scanf("%d", &target);
while(l <= r)
{
mid = (l+r)/2;
if(library[mid].year == target)
{
printf("\n%s",library[mid].title);
printf(" %d",library[mid].year);
printf("These are all the books with that year");
break;
}
else if (library[mid].year < target)
{
l = mid + 1;
}
else
{
r = mid - 1;
}
if(l > r)
printf("The target is not in the array.\n");
}
menu();
}
Upvotes: 0
Views: 1086
Reputation: 13955
You're doing a kind of binary search over the array, which is not designed to find all instances without modification. Have you considered just doing a linear search (i.e., a for
loop) over the length of the array and printing if the array element matches your search criteria? One might implement a naive linear search like this:
for (int i = 0; i<500; i++) {
if (library[i].year == target) {
// Do your printing here
}
// Otherwise do nothing!
}
Upvotes: 3