WAP to store the author,title and price of 5 books and display it.
Objective
Write a C++ program to store the author, title, and price of 5 books using a Structure.
Algorithm / Approach
- Define a
struct Bookwithauthor,title, andprice. - In
main(), declare an array of structures:Book b[5]. - Run a loop to read the details for each book.
- Use
cin.ignore(1, '\n')after reading the integer to clear the input buffer. - Run a second loop to print the details of all 5 books.
main.cpp
#include<iostream>
using namespace std;
struct Book {
string author;
string title;
int price;
};
int main() {
Book b[5];
for(int i = 0;i<5; i++) {
cout<<"Enter Author ";
getline(cin,b[i].author);
cout<<"Enter Title ";
getline(cin,b[i].title);
cout<<"Enter Price ";
cin>>b[i].price;
cin.ignore(1,'\n');
}
for(int i=0; i<5; i++) {
cout<< b[i].author<<"\t"<< b[i].title;
cout<<"\t"<< b[i].price<< endl;
}
return 0;
}
Expected Output
Enter Author Faiz Enter Title Java Enter Price 500 Enter Author Alok Enter Title C Enter Price 400 Enter Author Dan Enter Title C++ Enter Price 600 Enter Author Ayan Enter Title Android Enter Price 1000 Enter Author Bala Enter Title J2SE Enter Price 700 Faiz Java 500 Alok C 400 Dan C++ 600 Ayan Android 1000 Bala J2SE 700
Explanation of the Program
- A Structure (
struct) allows you to group different data types (like strings and integers) together under a single logical name, making it perfect for representing complex real-world objects like a "Book". - When creating an array of structures, every single slot in the array contains its own independent copy of the
author,title, andpricevariables.
Complexity
Time Complexity
O(n) - Where n is the number of books.
Space Complexity
O(n) - To store the array of structures.