Lab 5
Lab 5
24CPES201 – 24COMP02C
What is a Struct?
A struct (short for "structure") is a way to group multiple pieces of related data together
under one name. Think of it as a container that holds a collection of data, where each
piece of data (called a member) can have its own type and value. Structs are particularly
useful when you want to represent something complex that involves multiple attributes.
1. A title (text).
2. An author (text).
3. A year of publication (number).
4. A price (number).
Individually, you could create separate variables for each of these attributes:
• string title
• string author
• int year
• float price
But it’s easier to group them together into one entity called a Book.
Structs are essential when you need to represent entities that have multiple attributes.
They: Make code easier to read and manage. Allow you to handle more complex data
without confusion. Help reduce errors by logically grouping related variables.
1
Key Concepts:
1. Grouping Data:
o A struct allows you to combine different variables (of possibly different
types) into one logical unit.
o For example, a student struct could group together a student’s name, age,
and marks.
2. Logical Organization:
o Using structs makes your code cleaner and more organized because you
don’t need separate variables for related data.
o Instead of having string student1_name and int student1_age, you just
have Student student1.
3. Easy Access:
o Once you create a struct, you can access or modify its members using a
simple syntax.
o For example, if you have a Book struct, you can directly refer to
book1.title or book1.price.
4. Reusability:
o After defining a struct, you can create multiple instances of it. For
example, once you define a Car structure, you can create as many cars as
you need, each with its own brand, model, and year.
2
Exercise 1: Create and Use a Simple Structure
Design a C++ program to store and display information about a student using a
structure. The structure should have:
• ID
• Name
Tasks:
1. Define a structure named Student.
return 0;
}
3
Exercise 2: Structure Initialization
Write a program to manage a structure named Book. The structure should contain:
• Title (a string)
• Author (a string)
• Price (a float).
Tasks:
1. Create two structure variables for books.
3. Allow the user to input the details for the second book.
4. Display the details of both books.
#include <iostream>
#include<string>
using namespace std;
struct Book {
string title;
string author;
float price;
};
int main() {
// Initialize first book
Book book1 = { "C++ Programming", "Bjarne Stroustrup", 45.99 };
// Input second book
Book book2;
cout << "Enter book title: ";
cin.ignore();
getline(cin, book2.title);
cout << "Enter author: ";
getline(cin, book2.author);
cout << "Enter price: ";
cin >> book2.price;
return 0;
}
4
Exercise 3: Rectangle Properties
Create a structure called Rectangle with:
• Width (an integer)
• Height (an integer).
Tasks:
1. Declare a variable of the Rectangle structure type.
#include <iostream>
using namespace std;
struct Rectangle {
int width;
int height;
};
int main() {
Rectangle rect;
return 0;
}
5
Exercise 4: Structure with Functions
Problem:
Add a function inside the Rectangle structure to calculate the area.
#include <iostream>
using namespace std;
struct Rectangle {
int width;
int height;
int calculateArea() {
return width * height;
}
};
int main() {
Rectangle rect;
return 0;
}
6
Exercise 5: Array of Structures
Define a structure named Employee that has:
• Name (a string)
• Salary (a float).
Tasks:
1. Create an array of 3 Employee structures.
return 0;
}
7
Exercise 6: Nested Structures
Write a program that defines a structure Date with:
• Day (integer)
• Month (integer)
• Year (integer).
Tasks:
1. Create a variable of type Person.
2. Allow the user to input the person's name and date of birth.
3. Display the full name and date of birth in the format DD/MM/YYYY.
#include <iostream>
#include<string>
using namespace std;
struct Date {
int day;
int month;
int year;
};
struct Person {
string name;
Date dob;
};
int main() {
Person person;
// Display details
cout << "\nName: " << person.name << "\nDate of Birth: " <<
person.dob.day << "/"
<< person.dob.month << "/" << person.dob.year << endl;
return 0;
}
8
Exercise 7: Structure with Uninitialized Values
Problem:
Define a structure Car with uninitialized members and observe
the default values.
Answer:
#include <iostream>
using namespace std;
struct Car {
string make;
int year;
float mileage;
};
int main() {
// Declare a Car structure without initializing the members
Car myCar;
// Display default values of the uninitialized structure members
cout << "Default values of the uninitialized structure:\n";
cout << "Make: " << myCar.make << " (string defaults to an empty
string)\n";
cout << "Year: " << myCar.year << " (uninitialized integer, garbage
value)\n";
cout << "Mileage: " << myCar.mileage << " (uninitialized float, garbage
value)\n";
return 0;
}
9
Problem Description 8: Library Management System
You are tasked with creating a simple Library Management System. The program
should allow a borrower to select a book from a list of available books. If the book is
already borrowed, the program should notify the user. Otherwise, the book is marked as
borrowed, and the updated list of books is displayed.
Requirements
1. Book Structure:
o Each book has:
▪ title (string)
▪ author (string)
▪ isBorrowed (boolean) to track if the book is borrowed or not.
2. Borrower Structure:
o Each borrower has:
▪ name (string)
▪ borrowedBook (a Book structure)
▪ hasBook (boolean) to track if the borrower currently has a borrowed
book.
Program Features:
• Create a list of 3 books.
• Display all books, indicating which ones are already borrowed.
• Prompt the user to:
1. Enter their name.
2. Select a book to borrow by entering the book's number.
• Check if the selected book is already borrowed:
o If yes, display an appropriate message: "Sorry, the book is already
borrowed."
o If no, assign the book to the borrower and display a success message:
"You have successfully borrowed the book!"
• Display the updated list of books only if a book was successfully borrowed.
#include <iostream>
#include <string>
using namespace std;
struct Book {
string title;
string author;
bool isBorrowed = false; // Initialize with "not borrowed" status
};
struct Borrower {
string name;
Book borrowedBook;
bool hasBook = false;
};
10
int main() {
// Initialize 3 books
Book books[3] = {
{"C++ Primer", "Stanley Lippman", false},
{"Clean Code", "Robert C. Martin", false},
{"The Pragmatic Programmer", "Andrew Hunt", true}
};
Borrower borrower;
int choice;
cout << "Choose a book to borrow (1-3): ";
cin >> choice;
return 0;
}
11