0% found this document useful (0 votes)
6 views11 pages

Lab 5

The document provides an overview of structures in C++, explaining their purpose and benefits in organizing related data. It includes multiple exercises that guide the reader through creating and using structures for various applications such as managing student information, books, rectangles, employees, and a library management system. Each exercise is accompanied by example code to illustrate the concepts discussed.

Uploaded by

oe66552
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Lab 5

The document provides an overview of structures in C++, explaining their purpose and benefits in organizing related data. It includes multiple exercises that guide the reader through creating and using structures for various applications such as managing student information, books, rectangles, employees, and a library management system. Each exercise is accompanied by example code to illustrate the concepts discussed.

Uploaded by

oe66552
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Module Code:

24CPES201 – 24COMP02C

Module Leader: Module TA:


Dr. Sally Saad Eng. Ameera Amgad Amer
Eng. Malak Sayed
Week 11 Lab 5

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.

Imagine you want to describe a book. A book has:

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

• Grades (an array of 3 integers).

Tasks:
1. Define a structure named Student.

2. Declare a structure variable.


3. Allow the user to input values for the ID, Name, and Grades.

4. Display the entered information.


#include <iostream>
using namespace std;
struct Student {
int id;
char name[50];
int grades[3];
};
int main() {
Student stu;
// Input student details
cout << "Enter student ID: ";
cin >> stu.id;
cout << "Enter student name: ";
cin.ignore(); // Clear input buffer
cin.getline(stu.name, 50);
cout << "Enter 3 grades: ";
for (int i = 0; i < 3; i++) {
cin >> stu.grades[i];
}
// Display student details
cout << "\nStudent Details:\n";
cout << "ID: " << stu.id << "\nName: " << stu.name << "\nGrades: ";
for (int i = 0; i < 3; i++) {
cout << stu.grades[i] << " ";
}
cout << endl;

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.

2. Initialize the first book with some values during declaration.

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;

// Display book details


cout << "\nBook 1:\nTitle: " << book1.title << "\nAuthor: " <<
book1.author << "\nPrice: $" << book1.price << endl;
cout << "\nBook 2:\nTitle: " << book2.title << "\nAuthor: " <<
book2.author << "\nPrice: $" << book2.price << endl;

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.

2. Allow the user to input values for Width and Height.

3. Calculate and display the area and perimeter of the rectangle.

#include <iostream>
using namespace std;

struct Rectangle {
int width;
int height;
};

int main() {
Rectangle rect;

// Input rectangle dimensions


cout << "Enter width: ";
cin >> rect.width;
cout << "Enter height: ";
cin >> rect.height;

// Calculate and display properties


int area = rect.width * rect.height;
int perimeter = 2 * (rect.width + rect.height);
cout << "\nArea: " << area << "\nPerimeter: " << perimeter << endl;

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;

// Input rectangle dimensions


cout << "Enter width: ";
cin >> rect.width;
cout << "Enter height: ";
cin >> rect.height;

// Display area using the function


cout << "\nArea: " << rect.calculateArea() << endl;

return 0;
}

6
Exercise 5: Array of Structures
Define a structure named Employee that has:
• Name (a string)

• Age (an integer)

• Salary (a float).

Tasks:
1. Create an array of 3 Employee structures.

2. Allow the user to input data for each employee.

3. Display the details of the employee with the highest salary.


#include <iostream>
#include <string>
using namespace std;
struct Employee {
string name;
int age;
float salary;
};
int main() {
Employee employees[3];
// Input employee details
for (int i = 0; i < 3; i++) {
cout << "Enter details for employee " << i + 1 << ":\n";
cout << "Name: ";
cin.ignore();
getline(cin, employees[i].name);
cout << "Age: ";
cin >> employees[i].age;
cout << "Salary: ";
cin >> employees[i].salary;
}

// Find employee with the highest salary


int highestIndex = 0;
for (int i = 1; i < 3; i++) {
if (employees[i].salary > employees[highestIndex].salary) {
highestIndex = i;
}
}
// Display the employee with the highest salary
cout << "\nEmployee with the highest salary:\n";
cout << "Name: " << employees[highestIndex].name << "\nAge: " <<
employees[highestIndex].age
<< "\nSalary: $" << employees[highestIndex].salary << endl;

return 0;
}

7
Exercise 6: Nested Structures
Write a program that defines a structure Date with:
• Day (integer)

• Month (integer)

• Year (integer).

Then define a structure Person that includes:


• Name (string)

• DateOfBirth (a Date structure).

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;

// Input person's details


cout << "Enter name: ";
getline(cin, person.name);
cout << "Enter date of birth (day month year): ";
cin >> person.dob.day >> person.dob.month >> person.dob.year;

// 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";

// Initialize members to demonstrate proper usage


myCar.make = "Toyota";
myCar.year = 2023;
myCar.mileage = 15000.5;

cout << "\nAfter initialization:\n";


cout << "Make: " << myCar.make << "\nYear: " << myCar.year << "\nMileage:
" << myCar.mileage << endl;

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;

// Display available books


cout << "Available Books:\n";
for (int i = 0; i < 3; i++) {
cout << i + 1 << ". " << books[i].title
<< " by " << books[i].author
<< (books[i].isBorrowed ? " (Already Borrowed)" : "") << endl;
}

// Borrower borrows a book


cout << "\nEnter borrower name: ";
getline(cin, borrower.name);

int choice;
cout << "Choose a book to borrow (1-3): ";
cin >> choice;

if (choice < 1 || choice > 3) {


cout << "Invalid choice. Please select a valid book number.\n";
}
else if (books[choice - 1].isBorrowed) {
cout << "Sorry, the book \"" << books[choice - 1].title << "\" is
already borrowed.\n";
}
else {
// Allow borrower to borrow the book
borrower.borrowedBook = books[choice - 1];
borrower.hasBook = true;
books[choice - 1].isBorrowed = true;
cout << borrower.name << " successfully borrowed \"" <<
borrower.borrowedBook.title << "\".\n";

// Display the updated list of books only if borrowing was successful


cout << "\nUpdated Book List:\n";
for (int i = 0; i < 3; i++) {
cout << i + 1 << ". " << books[i].title
<< " by " << books[i].author
<< (books[i].isBorrowed ? " (Already Borrowed)" : "") <<
endl;
}
}

return 0;
}

11

You might also like