0% found this document useful (0 votes)
13 views

Final Term Lab Final

Uploaded by

Haisum Haroon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Final Term Lab Final

Uploaded by

Haisum Haroon
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Final Term (Lab Exam)

Time Allowed: 3 hours Total Marks: 100


Instructions
● You need to create separate projects for each problem.
● Modify the starter code to meet the requirements of the problems.
● The code has to be written in multiple files (a separate .h and .cpp for a C++
project and a separate .py file for a Python class). Failing to do so will result in
deduction of marks.
● Problems 1 and 3 have to be implemented in C++ while Problem 2 has to be
implemented in Python.
● The use of internet (other than downloading the paper from Google Classroom
and Uploading the solution to the Google Classroom) is prohibited.
● The paper will be canceled and case will be forwarded to the disciplinary
committee in case of taking help from any internet source or any code other
than the one provided as part of the question paper.

Install and Configure SQLite


Download SQLite (https://www.sqlite.org/download.html)
Extract the zip file
Add sqlite3.c to your project
Go to “Manage NuGet Packages” -> In Browse tab, search for sqlite3_c_plus_plus -> install the
package
#include <sqlite3.h>, and you are good to go

Install/Download SQLite DB Browser (Optional)


Download DB Browser for SQLite - no installer (https://sqlitebrowser.org/dl/)
Extract the zip file
In the extracted folder, open “DB Browser for SQLite.exe”

Problem 1 [55 Marks]


You need to develop a library management system where main.cpp displays user with the text-based
menu to perform the following operations:

1. Add a new book to the library


a) Register a new book
b) Add more copies of an existing book
The user will enter a book’s name and if it exists in the DB, it will be prompted to enter the copies
you want to add to the existing ones. Otherwise, it will prompt the user to enter the detail of the
new book along with the number of copies
2. Register a new member
Prompt the user to enter the complete detail of a new member.
3. Issue a book to a member
Prompt the user to enter Book Id and Member Id and issue the book if there is no violation of
business (library) rules.
4. Record a book return by a member (given the book title and member name)
5. Given a member name, display all the books (book title only) issued to him
6. Given a member name, display all the books (book title only) returned by him
7. Given a book title, display the member who have been issued the title and have not yet
returned
8. Given a book Id, display the title, publisher, available copies and total copies of the book Id
Database Tables
For a book, you will need to create Books database table with the following attributes (their purpose is
self-explanatory):
Book Id, Title, Publisher, Total Copies, Available Copies

To keep record of the books issued, BookIssues table will have the following attributes:
Book Id, Member Id, Issue Data, Expected Return Date, Is Returned

For a member, the database table Members will have the following attributes:
Member Id, Member Name, Address

Classes
You will need to define the following classes:
Book, Member, BookIssue - for book, member and book issue objects
Library - It will implement the logic of business rules and will be between the user interface and
database class.
Database - It will implement the functionality of saving and retrieving data from the SQLite database.

Business Rules
A member will not be issued book if he has already borrowed one and has not returned it as yet.
A book will not be issued if its available copies are 0.
A book can have a maximum of 10 copies.

Starter Code
Following is the code to connect to an SQLite3 DB:
You need to declare a member of the Database class:
sqlite3 *db;
const char* dbPath = “---write your DB path here---”;

int return_code = sqlite3_open(dbPath, &db); //return_code will be 0 if the operation is successful.

Following code will close the DB connection:


sqlite3_close(db);

Following is the code to create DB tables:


//define the sql statement for creating the Books table
const char* sqlCommand = R"(CREATE TABLE IF NOT EXISTS Books (
BookID INTEGER PRIMARY KEY AUTOINCREMENT,
Title TEXT,
Publisher TEXT,
TotalCopies INTEGER,
AvailableCopies INTEGER
);)";

//declare a string for holding error message


char* errMsg = nullptr;

int rc = sqlite3_exec(db, sqlCommand, nullptr, nullptr, &errMsg);


if (rc != SQLITE_OK) {
std::cerr << "Error creating table: " << errMsg << std::endl;
sqlite3_free(errMsg);
}

Following is the code to insert a record into the table:


const char* sql = "INSERT INTO Books (Title, Publisher, TotalCopies, AvailableCopies) VALUES
(?, ?, ?, ?);";

//prepare statement for the sql command


sqlite3_stmt* stmt;
int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK) {
std::cerr << "Cannot prepare statement: " << sqlite3_errmsg(db) << std::endl;

const char* title = "dummy title";


const char* publisher = "dummy publisher";
int totalCopies{ 5 };
int availableCopies{ 3 };
sqlite3_bind_text(stmt, 1, title, -1, SQLITE_STATIC);
sqlite3_bind_text(stmt, 2, publisher, -1, SQLITE_STATIC);
sqlite3_bind_int(stmt, 3, totalCopies);
sqlite3_bind_int(stmt, 4, availableCopies);

//execute the statement


rc = sqlite3_step(stmt);

if (rc != SQLITE_DONE) {
std::cerr << "Record not entered becuase of : " << sqlite3_errmsg(db) << std::endl;
}

//release resources
sqlite3_finalize(stmt);

Following is the code to retrieve two column values from a table based on a condition:
const char* sql = "SELECT Title, TotalCopies FROM Books WHERE AvailableCopies < ?;";
sqlite3_stmt* stmt;
std::vector<std::pair<std::string, int>> retrieved_books;

int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);


if (rc != SQLITE_OK) {
std::cerr << "Cannot prepare statement: " << sqlite3_errmsg(db) << std::endl;
}

int available_value{5};
sqlite3_bind_int(stmt, 1, available_value);

//use the following variation if the condition is a string variable (e.g., publisher):
//sqlite3_bind_text(stmt, 1, publisher.c_str(), -1, SQLITE_STATIC);

while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {


std::string title = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
int totalCopies = sqlite3_column_int(stmt, 1);
retrieved_books.push_back(std::make_pair(title, totalCopies));
}

if (rc != SQLITE_DONE) {
std::cerr << "Execution failed: " << sqlite3_errmsg(db) << std::endl;
}

sqlite3_finalize(stmt);

Following code prints the values retrieved from the DB (and saved int a vector of pairs):
for (const auto& book : retrieved_books) {
std::cout << "Title: " << book.first << ", Total Copies: " << book.second << std::endl;
}

Problem 2 [20 Marks]


Develop the same project in Python. But include the following functionality only:
1. Given a member name, display all the books (book title only) issued to him
2. Given a member name, display all the books (book title only) returned by him
3. Given a book title, display the member who have been issued the title and have not yet
returned
4. Given a book Id, display the title, publisher, available copies and total copies of the book Id

Starter Code
Following is the code to connect to the database:
#it will create an object named conn to connect to the DB
self.conn = sqlite3.connect(dbPath)

#it will create a cursor object associated with the conn object.
self.cur = self.conn.cursor()

Following is the code to create a table:


self.cur.execute('''CREATE TABLE IF NOT EXISTS Books ( BookId INTEGER PRIMARY KEY,
Title TEXT,
AuthorId INTEGER,
Publisher TEXT,
PublicationYear INTEGER)''')

#at the end you need to call the commit() method of the conn object.
self.conn.commit()

Following is the code to insert a record into the DB table:


try:

self.cur.execute("INSERT INTO Books (Title, AuthorId, Publisher, PublicationYear) VALUES


(?, ?, ?, ?)", (title, author_id, publisher, year))

self.conn.commit()

except sqlite3.Error as e: #if an exception occurs


#code to handle exception

Following is the code to retrieve data:


Author_id = 10 #get the record for this author
try:
#query the database through self.cur object
self.cur.execute("SELECT Title, Publisher, Edition FROM Books WHERE AuthorId=?",
(author_id,))

#fetch all the books of the provided author_id


books_data = self.cur.fetchall()

#iterate through all the records fetched from the DB


for book_data in books_data:
title, publisher, edition = book_data

except sqlite3.Error as e:
#handle if any run time error occurs

Problem 3 [25 Marks]


Write the code of a class named Matrix that use a single int pointer to allocate memory for a matrix
(the constructor accepts the number of rows and columns). Each element of the matrix should have a
value of (i+1 * j+1) (where i is the row number and j is the column number). The member printMatrix()
prints the elements of the matrix row and column wise.
Overload the + and - operators where for both the operations the operands are two matrices (and
both return a third matrix).
The overloaded + operator will return a matrix with the dimensions that are sum of the dimensions of
the operand matrices (i1 + i2, j1 + j2) .
The overloaded - operator will return a matrix with the dimensions obtained after subtracting the
second operand’s dimension from the first operand’s dimensions (i1 - i2, j1 - j2).
Each element values of the resulting matrix must be (i+1 * j+1).

You might also like