Lab Solution
Lab Solution
Mark Maverick
Solutions
Objective:
The objective of this lab is to teach students how to install and use the
Dev-C++ and online compilers.
Learning Outcomes:
After this lab, the students will be able to run the C++ code in Dev-C++
and the online compilers.
Problem Statement
Installation Steps:
Step 1:
Step 2:
Step 3:
Step 5:
Step 7:
Your Dev C++ 4.9.9.2 has been installed successfully. Now start writing
compiling and running programs and enjoy programming.
Step 1:
Step 2:
Step 3:
Step 5:
Step 7:
Your Dev C++ 4.9.9.2 has been installed successfully. Now start writing
compiling and running programs and enjoy programming.
1st Step:
2nd Step:
How to compile the program:
1st Step:
2nd and 3rd step will be performed automatically
2nd Step:
3rd Step:
How to run the program:
Output will be displayed as:
Guidelines on how to use online C++ compiler
Following are the steps to write, compile, and run a program using an
online compiler:
Open a browser and type the following address in the address bar.
https://www.programiz.com/cpp-programming/online-compiler/
If the program contains syntax errors, then errors will be shown along with
the line number in the highlighted area.
After removing the syntax errors, click on the ‘Run’ button again to see
the output.
Lab 1-2: Object Orientation
Objective:
The objective of this lab is to teach students how to identify objects, their
attributes and behaviors from the real-world scenario.
Learning Outcomes:
After this lab, the students will be able to identify objects, attributes and
behaviors from a given scenario.
Problem Statement
Consider the following scenario and identify all objects, their attributes,
and behaviors.
You are required to extract the Class Name, attributes and behaviours
(operations) from the above scenario.
Solution:
Objective:
The objective of this lab is to teach students how to identify classes and
relationships between classes and draw a UML class diagram by applying
the concepts of inheritance, aggregation or composition.
Learning Outcomes:
After this lab, the students will be able to draw a UML class diagram for a
given scenario.
Problem Statement
Solution:
Lab 3: Constructor overloading and copy constructor
Objective:
Learning Outcomes:
After this lab, the students will be able to overload constructors, copy
constructors, and destructors.
Problem Statement
Write a C++ program that consists of a class named Employee having the
following data members:
Employee id
Employee name
Employee salary
Within the main () function, create an object emp1 of class Employee and
initialize its data members using a parameterized constructor. Within the
constructor, you have to call the setters functions to set the values of
these data members.
Now, create another object emp2 and initialize it with emp1 using the
deep copy constructor.
After that, you have to call the display () function to show the data
members of both objects.
Sample Output:
#include <iostream>
#include <string.h>
using namespace std;
class Employee{
private:
int empId;
char *empName;
float empSalary;
public:
void setId(int id){
empId = id;
}
void setName(char *name){
empName = new char[strlen(name)+1];
strcpy(empName, name);
}
void setSalary(float salary){
empSalary = salary;
}
int getId(){
return empId;
}
const char *getName(){
return empName;
}
float getSalary(){
return empSalary;
}
Employee(){
empId = 0;
empName = NULL;
empSalary = 0.0;
}
Employee(int id, char *name, float salary){
setId(id);
setName(name);
setSalary(salary);
}
void Display(){
cout << "Employee ID: " << getId() << endl;
cout << "Employee Name" << getName() << endl;
cout << "Employee Salary" << getSalary() << endl;
}
~Employee(){
delete[]empName;
}
};
int main(){
Employee emp1(100, "Mark", 50000);
Employee emp2 = emp1; // Copy constructor called
cout << "The Data Members of Object 01:" << endl;
emp1.Display();
cout << "The Data Members of Object 02:" << endl;
emp2.Display();
return 0;
}
Objective:
The objective of this lab is to teach students how to define and use
constant and static members in classes.
Learning Outcomes:
After this lab, the students will be able to define and use constant and
static members in classes.
Problem Statement
Write a C++ program that creates a class named Employee having the
following data members:
A static data member “count” to store the total number of Employee
objects
Employee ID as a const data member
In the main () function, create three objects e1, e2, and e3 of type
Employee and initialize the value of employee id.
Also, create a constant object ‘e4’ of an Employee class and initialize the
employee ID.
For each object, print the value of Employee ID using the const member
function.
At the end of program, display the value of the “count” data member
showing the total number of employees.
Sample Output:
#include <iostream>
using namespace std;
class Employee{
private:
static int count;
const int empId;
public:
static int getCount(){
return count;
}
int getId() const{
return empId;
}
Employee(): empId(0){}
Employee(int id): empId(id){
count++;
}
~Employee(){
count--;
}
};
int Employee::count = 0;
int main(){
Employee e1(10);
cout << "Employee Id: " << e1.getId() << endl;
Employee e2(20);
cout << "Employee Id: " << e2.getId() << endl;
Employee e3(30);
cout << "Employee Id: " << e3.getId() << endl;
const Employee e4(40);
cout << "Employee Id: " << e4.getId() << endl;
cout << "Totoal Objects After Creation: " << Employee::getCount()
<< endl;
return 0;
}
Lab 5: Composition
Objective:
Learning Outcomes:
After this lab, the students can write C++ code for the composition
relationships between classes.
Problem Statement
Now, call the deposit() function to deposit some amount then call the print
() function which will display all the values of Customer including their ID,
name, CNIC, address and account details.
Then, call the withdraw function to withdraw some amount and call the
print () function which will display all the values of Customer including
their ID, name, CNIC, address and account details.
Sample Output:
class Account
{
private:
int accNo;
float balance;
char *bankName;
int branchCode;
public:
Account(int no, float b, char *bName, int bCode)
{
accNo = no;
balance = b;
bankName = new char[strlen(bName) + 1];
strcpy(bankName, bName);
branchCode = bCode;
}
void print()
{
cout << "Account Number: " << accNo << endl;
cout << "Bank Name: " << bankName << endl;
cout << "Branch Code: " << branchCode << endl;
cout << "Balance: " << balance << endl
<< endl;
}
~Account()
{
delete[] bankName;
}
};
class Customer
{
private:
int cusId;
char *cusName;
char *cusCNIC;
char *cusAddress;
Account acc;
public:
Customer(int id, char *name, char *cnic, char *address, int no,
float b, char *bName, int bCode) : acc(no, b, bName, bCode)
{
cusId = id;
cusName = new char[strlen(name) + 1];
strcpy(cusName, name);
cusCNIC = new char[strlen(cnic) + 1];
strcpy(cusCNIC, cnic);
cusAddress = new char[strlen(address) + 1];
strcpy(cusAddress, address);
}
void deposit(float amount)
{
acc.deposit(amount);
}
~Customer()
{
delete[] cusName;
delete[] cusCNIC;
delete[] cusAddress;
}
};
int main()
{
Customer cus(10, "abc", "35204-7458545-9", "Lahore", 1, 50000,
"HBL", 1924);
cout << "Customer infomration having initial amoount (50000) is
given below:" << endl
<< endl;
cus.print();
cout << "Customer information after depositing amount (10000) is
given below:" << endl
<< endl;
cus.deposit(10000);
cus.print();
cout << "Customer inofmration after withdrawing amount (20000) is
given below:" << endl
<< endl;
cus.withdraw(20000);
cus.print();
system("pause");
return 0;
}
Lab 6: Operator Overloading
Objective:
Problem Statement
Create a class named Circle. Perform following tasks for this class.
a. Add one data member radius of type double.
b. Add setter and getter functions to set and get value of
radius data member.
c. Create following objects: circle1, circle2, cricle3, circle4,
circle5 and cricle6
of Circle class in main() function.
d. Set radius of circle1, circle2, and cricle3 to 6.3, 4.2, and 12.5
respectively.
e. Overload the + operator for the following types of
operations.
i. circle4 = circle1 + circle2
ii. circle5 = circle2 + 8.23
iii. circle6 = 7.4 + circle2;
f. Display radius of circle4, circle5 and cricle6.
Sample Output:
Write C++ code to overload -, *, and / operators for the given class
circle.
Solution:
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
void setRadius(double r) {
radius = r;
}
double getRadius( ){
return radius;
}
//Overloading of + operator to support operation: circle4 = circle1 +
circle2
Circle operator + (const Circle& c) {
Circle temp;
temp.radius = this->radius + c.radius;
return temp;
}
//Overloading of + operator to support operation: circle2 + 8.23 (any
double value)
Circle operator + (const double value) {
Circle temp;
temp.radius = this->radius + value;
return temp;
}
//Overloading of + operator to support operation: 7.4 (any double
value) + circle2;
friend Circle operator + (const double value, const Circle& c)
{
Circle temp;
temp.radius = value + c.radius;
return temp;
}
};
int main( ) {
Circle circle1, circle2, cricle3, circle4, circle5, circle6;
circle1.setRadius(6.3);
circle2.setRadius(4.2);
cricle3.setRadius(12.5);
circle4 = circle1 + circle2;// + circle3;
circle5 = circle2 + 8.23;
circle6 = 7.4 + circle2;
cout << "Radius of Circle 4 : " << circle4.getRadius()
<<endl<<endl<<endl;
cout << "Radius of Circle 5 : " << circle5.getRadius()
<<endl<<endl<<endl;
cout << "Radius of Circle 6 : " << circle6.getRadius()
<<endl<<endl<<endl;
}
Lab 7: Overloading stream insertion, stream extraction and unary
operators
Objective:
Problem Statement
#include<iostream>
using namespace std;
class Complex
{
private:
int real, imag; //declaration of real and imaginary part of the
complex number
public:
Complex(int r = 0, int i =0) //Parametrized Constructor
{
real = r; //assign the value
imag = i; //assign the value
}
int main()
{
Complex com1; //Creation of object of class Complex
cin >> com1; //This will call the insertion operator
function
cout << "The Complex object com1 is: ";
cout << com1; //This will call the extraction operator
function
Complex com2=-com1;
cout << "The Complex object com2 is: ";
cout<<com2;
Complex com3=++com1;
cout << "The Complex object com3 is: ";
cout<<com3;
Complex com4=com3++;
cout << "The Complex object com4 is: ";
cout<<com4;
return 0;
}
Lab 8: Inheritance
Objective:
Problem Statement
Write a C++ program that consists of a class named Planet which has no
data member and only contains a default constructor. Your program
should contain two more classes Inner_Planet and Outer_Planet. Both
of these classes should also contain a default constructor. Your program
should implement the concept of inheritance between “Planet class,
Inner_Planet class, and Outer_Planet class”.
Sample Output
After running your program, the following output screen should display.
Solution:
#include<iostream>
#include<conio.h>
using namespace std;
class Planet
{
public:
Planet() //Default constructor of parent class Planet
{
cout<<"Planet Constructor is called"<<endl;
}
};
cout<<"\n";
system("pause");
}
Lab 09:
Objective:
Problem Statement
1. Base
2. Derived_Private
3. Derived_Protected
4. Derived_Public
secret private
protect protected
access public
Other three classes should be inherited from “Base” class with respect to
following type of inheritance.
Derived_Private Private
Derived_Protected Protected
Derived_Public Public
All three derived classes should contain show() function, which should
display the values of secret, protect and access data member of base
class. On running this program, your compiler will generate compile time
errors. Carefully observe for which type of base class data member,
compiler is generating error.
Class Diagram
Compilation Results
Solution:
#include<iostream>
using namespace std;
class Base
{
private:
int secret; //Declaration of variable “secret” that is
private.
protected:
int protect; //Declaration of variable “protect” that is
protected.
public:
int access; //Declaration of variable “access” that is
public.
Base() //Constructor of base class.
{
//Assignment of default value to
variables.
access=0;
protect=0;
secret=0;
}
};
//private inheritance between Base(parent) and Derived_Private(child)
class. It makes the public and protected //members of the base class
private in the derived class.
class Derived_Private: private Base
{
public:
void show() //show function to display the values of
variable.
{
cout<<access<<endl;
cout<<protect;
cout<<secret;
}
};
//protected inheritance between Base(parent) and
Derived_Protected(child) class. It makes the public and //protected
members of the base class protected in the derived class.
class Derived_Protected: protected Base
{
public:
void show() //show function to display the values of variable.
{
cout<<access;
cout<<protect;
cout<<secret;
}
};
//protected inheritance between Base(parent) and Derived_Public(child)
class. It makes public members of the //base class public in the
derived class, and the protected members of the base class remain
protected in the //derived class.
class Derived_Public: public Base
{
public:
void show() //show function to display the values of
variable.
{
cout<<access;
cout<<secret;
cout<<protect;
}
};
int main()
{
Derived_Public child1; //Object of Derived class
cout<<"This is accessibility of base data members in derived class
in case of public inheritance"<<endl;
child1.show(); //call the show function
Objective:
Problem Statement
Consider the given class diagram and perform the tasks given below.
Part (1):
PlainBox
LunchBox
GiftBox
“LunchBox” and “GiftBox” classes should be publicly inherited from
PlainBox Class.
All three classes should contain Display() function, which should display
respective class name.
Sample Output
Solution:
Solution
#include<iostream>
using namespace std;
class plainBox //Base Class
{
public:
void display() //Display Function to display “Plain Box Class”.
{
cout<<"Plain Box Class"<<endl;
}
};
Part (2):
Make Display() function of “PlainBox” class virtual and then run the
program. Your output should be as follows:
Sample Output
Solution:
#include<iostream>
using namespace std;
class plainBox //Base Class
{
public:
virtual void display()
//A virtual function is a member function within the base class that we
redefine in a derived class. It is //declared using the virtual
keyword. When a class containing virtual function is inherited, the
derived //class redefines the virtual function to suit its own needs.
{
cout<<"Plain Box Class"<<endl; //Display Function to display
“Plain Box Class”.
}
};
class LunchBox: public plainBox //LunchBox(child) class is inherited
from the PlainBox(parent) class.
{
public:
void display()
{
cout<<"Lunch Box Class"<<endl; //Display Function to display
“Lunch Box Class”.
}
};
class GiftBox: public plainBox //GiftBox(child) class is inherited
from the PlainBox(parent) class.
{
public:
void display()
{
cout<<"Gift Box Called"<<endl; //Display Function to display
“Gift Box Class”.
}
};
int main()
{
plainBox *LB= new LunchBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named LB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new LunchBox(). This new keyword
creates an LB object with dynamic storage duration and then returns a
pointer to it.
LB->display(); //Calling Display Function.
plainBox *GB= new GiftBox();
//This statement is creating an object dynamically and binds its
address to a pointer.
//This is the declaration of variable named GB which is a pointer to a
plainBox. This pointer object has automatic storage duration. It is
then initialized with the result of new GiftBox(). This new keyword
creates an GB object with dynamic storage duration and then returns a
pointer to it.
GB->display(); //Calling Display Function.
system("pause");
return 0;
}
Objective:
Learning Outcomes:
Problem Statement:
Write C++ code for a class Temp. The Class does not have any data
member but a member function “Compare()”. The function accepts two
values either integer, double, characters, or strings, and compares them.
The function returns true if the two passed values are equal otherwise
returns false.
Sample Output:
Practice Questions:
Write a C++ code for swapping the data of two variables. The
variables can be of any type (int, float, char etc.) using the function
templates.
Write a C++ Program to find the Sum of an Array using a class
template. The array elements can be int, float, and double types.
Character type data is not allowed.
Write a C++ Program to find the Square of a number using a single
template class. The number can be an integer, float, or double data
type.
Solution:
#include<iostream>
#include<string>
using namespace std;
class temp
{
public:
template <typename T> //Template
bool compare(T first, T second) //Function to compare two
values of any type.
{
if(first==second) //if the first value is equal to second
value
{
return true; //Then it return the true
}
else
{
return false; //if values are not equal it returns
false
}
}
};
int main()
{
temp t1,t2,t3,t4; //Object creation of type temp
bool r1,r2,r3,r4;
int a=10, b=20; //variables of integer type.
cout<<endl<<"Passing Integer to Function"<<endl;
r1=t1.compare(a,b); //Calling the compare function with two
integer variables.
if(r1==true) //if the function returns true it will print the
given cout statement.
{
cout<<a<<" and "<<b<<" are equal"<<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<a<<" and "<<b<<" are not equal" <<endl;
}
float c=10.0, d=30.9; //variables of Float type.
cout<<endl<<"Passing floats to Function"<<endl;
r3=t3.compare(c, d); //Calling the compare function with two float
variables.
if(r3==true) //if the function returns true it will print the given
cout statement.
{
cout<<c<<" and "<<d<<" are equal"<<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<c<<" and "<<d<<" are not equal"<<endl;
}
//variables of string type.
string str1="Pakistan";
string str2="Pakistan";
cout<<endl<<"Passing strings to Function"<<endl;
r2=t2.compare(str1, str2); //Calling the compare function with two
string variables.
if(r2==true) //if the function returns true it will print the
given cout statement.
{
cout<<str1<<" and "<<str2<<" are equal" <<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<str1<<" and "<<str2<<" are not equal" <<endl;
}
string str3="Hello";
string str4="hello";
cout<<endl<<"Passing strings with case sensitivity to
Function"<<endl;
r4=t4.compare(str3, str4); //Calling the compare function with two
string variables.
if(r4==true) //if the function returns true it will print the
given cout statement.
{
cout<<str3<<" and "<<str4<<" are equal" <<endl;
}
else //if the function returns false it will print the given cout
statement.
{
cout<<str3<<" and "<<str4<<" are not equal" <<endl;
}
system("pause");
return 0;
}
Lab 12: Class Templates, General, Partial, and Complete
Specialization
Covering Lectures: 34 - 36
Objective:
Learning Outcomes:
After completing this lab, students can practice General, Partial, and
Complete Specialization in programs.
Part a.
Problem Statement:
Write a C++ code for a generic class “Container” that stores two values of
potentially different types. The goal is to demonstrate:
Solution:
#include<iostream>
#include<typeinfo>
using namespace std;
return 0;
}
Lab 13: Templates, Inheritance, Friends
Objective:
This Lab aims to give students a deep understanding of the basic use of
Part a.
Problem Statement:
Write a C++ code for a template-based class Shape with two derived
classes Rectangle and Circle. Derived classes are also template classes.
Sample Output:
Part b.
Problem Statement:
Write C++ code for the following template readData and Subtract classes.
Subtract class is the friend of the ReadData class and can access the
private data members of the Subtract class.
The read() method of the Subtract class takes input from the user for both
data members.
In the Subt() function create two objects of ReadData for int and float,
perform subtraction on the data for both objects, and print the result for
each datatype.
Sample Output:
Practice Questions:
Solution:
Part a:
#include <iostream>
#include <cmath> // For M_PI constant
using namespace std;
public:
Rectangle(T l, T w) : length(l), width(w) {}
public:
Circle(T r) : radius(r) {}
// Main function
int main() {
cout<<"\n\n****Area of Rectangle and Circle for Integer Type of
Data****"<<endl;
// Create instances of Rectangle and Circle with integer type
Rectangle<int> rect(10, 5);
Circle<int> circ(6);
return 0;
}
Part b:
#include <iostream>
#include <conio.h>
using namespace std;
template <class T> // Template Class
class readData
{
T a; // private variable "a" of T type.
T b; // private variable "b" of T type.
public:
friend class Subtract; // class Subtract is friend of class
readData which means class Subtract can access the private data members
of class readData without any error.
void read() // Read function to take input from the user
{
cout << "\nEnter First Number : ";
cin >> a;
cout << "\nEnter Second Number : ";
cin >> b;
}
};
class Subtract
{
public:
void Sub()
{
readData<int> obj1; // int type object
readData<float> obj2; // float type object
int main()
{
Objective:
Learning Outcomes:
Problem Statement:
Use a map to store books with the book title as the key and the
book's information (author, publication year, etc.) as the value.
Use a queue to manage a waiting list for borrowing a book.
Use a vector to store the list of currently available books.
Implement functionality for adding books, borrowing books, and
managing the waiting list.
Sample Output:
Practice Questions:
Write a program that reads a string from the user, splits it into
words, and uses set to display all unique words in the string.
Create a task scheduler that allows the users to add tasks with
different priorities (higher numbers indicate higher priority). The
tasks should be stored in a priority_queue, and the program should
always execute and remove the highest-priority task first.
Solution:
#include <iostream>
#include <map>
#include <queue>
#include <vector>
#include <string>
using namespace std;
struct Book {
string author;
int publicationYear;
};
int main() {
map<string, Book> library;
queue<string> waitlist;
vector<string> availableBooks;
int choice;
string title, author;
int year;
while (true) {
cout << "\n****Select the Option****\n";
cout << "\n1. Add Book\n2. Borrow Book\n3. Manage Waitlist\n4.
Exit\n";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter book title: ";
getline(cin, title);
cout << "Enter author: ";
getline(cin, author);
cout << "Enter publication year: ";
cin >> year;
library[title] = {author, year};
availableBooks.push_back(title);
cout << "Book added!\n";
break;
case 2:
if (availableBooks.empty()) {
cout << "No books available, added to waitlist.\n";
cout << "Enter your name: ";
cin.ignore();
getline(cin, title);
waitlist.push(title);
} else {
cout << "You borrowed: " << availableBooks.back()
<< endl;
availableBooks.pop_back();
}
break;
case 3:
if (!waitlist.empty()) {
cout << "Next in waitlist: " << waitlist.front() <<
endl;
waitlist.pop();
} else {
cout << "No one in the waitlist.\n";
}
break;
case 4:
return 0;
default:
cout << "Invalid choice. Try again.\n";
}
}
}
Lab 15: Exception Handling
Objective:
Learning Outcomes:
After completing this lab students will be able to practice different error-
handling techniques:
Abnormal Termination
Graceful termination
Return the illegal value
Return error code from function
Exception handling.
Problem Statement:
Write a C++ program to create a method that takes a string as input that
must have vowels in it. For example, “Hello” is a valid input as it has two
vowels ‘e’ and ‘o’ while “XYZ” is not a valid input as the string has no
vowels.
Suppose a user enters a string with no vowel so arises an error. Apply the
given Error handling techniques to handle this error in your program.
Graceful termination
Exception handling.
Sample Output:
Practice Questions:
Write C++ programs for the above scenario using the given Error-Handling
techniques.
Abnormal Termination
Return the illegal value
Return error code from function
Solution:
#include <iostream>
#include <string>
#include <stdexcept>
// a. Graceful Termination
void gracefulTermination(const string& input) {
if (!hasVowels(input)) {
cout << "No vowels found! Gracefully terminating the program."
<< endl;
exit(1); // Graceful exit without abrupt termination
}
else
cout << "The string \"" << input << "\" is valid." << endl;
}
// b. Exception Handling
bool exceptionHandling(const string& input)
{
if (!hasVowels(input)) {
cout << "Error: No vowels found in the string!" << endl;
return false; // Indicate failure
}
cout << "The string \"" << input << "\" is valid." << endl;
return true; // Indicate success
}
int main() {
string input;
int in;
switch (in) {
case 1:
{
cout << "\n--- Graceful Termination ---\n";
gracefulTermination(input);
break;
}
case 2:
{
cout << "\n--- Exception Handling ---\n";
exceptionHandling(input);
break;
}
case 3:
return 0;
default:
std::cout << "Invalid choice.\n";
}
return 0;
}