Write a program that define a structure to store id, pages and price of a book.It declares an array of structure to store record of five books. It
inputs the records of five books and display the records of most costly book..
struct library{
string id;
int pages,price;
};
int main() {
library book[5];
int num,i;
cout<<"How many Book's Record do you want to Enter: ";
cin>>num;
for (i=1;i<=num;i++) {
cout<<endl<<"Enter the Record of Book: "<<i;
cout<<endl<<"Enter the Id of Book: ";
cin>>book[i].id;
cout<<endl<<"Enter the number of pages: ";
cin>>book[i].pages;
cout<<endl<<"Enter the Price of Book: ";
cin>>book[i].price;
}
for(i=1;i<=num;i++) {
if(book[0].price>book[i].price ) {
book[0].price=book[i].price;
cout<<endl<<"Book's id: "<<book[i].id;
cout<<endl<<"Book's Pages: "<<book[i].pages;
}
}
return 0;
}.
problem is i don't know how to print only the costly book record
.. yes i compiled it.. no error show it run correctly but not print the record of costly book .. please help me what condition use in it?
In addition to the index problem, you are doing too much in the second loop. The second loop should be trying to find the book with the max price. AFTER that loop, you print the info for the book.
When finding the book with the max price, keep a separate variable that is the index of that book.
You do read the data of 'num' books and store it is into the library (lines 10-19). You don't write anything to book[0] and you will have an out-of-range error, if 'num' is larger than 4.
On line 21 you do compare the price of the num books to the price of book[0], which has never been set.
Should the conditional expression return true, you will (finally) set the price of book[0] -- and print id & pages of the current book?
What you should do is to figure out the index of the book that has highest price. The std::max_element would help in that, but I presume that the purpose of your homework is to teach you to think, rather than to use modern C++ efficiently.
The loop in which you update your guess about the index should not print anything. When the loop has completed and the index indeed points to the most expensive tome, then you do use the index to display the records of the book.