LAB O2 (SOLUTIONS)
Task 01: Creating A Program with Classes and Objects
Write a C++ program that uses classes and objects to calculate the area of a rectangle, circle, or square
based on the user's choice and the dimensions they provide.
#include <iostream>
using namespace std;
class Rectangle{
public:
double height, width, area;
Rectangle(){
cout << "You chose rectangle.";
cout<<endl;
cin >> width >> height;
area=width * height;
cout << "The area of Rectangle is: " << area;
};
class Circle{
public:
double radius,area;
Circle(){
cout << "You chose circle."<<endl;
cout << "Enter the radius of circle: ";
cin >> radius;
area= 3.14759 * radius * radius;
cout << "Area of circle is: " << area;
};
class Square{
public:
double length, area;
Square(){
cout << "You chose square"<<endl;
cout << "Enter the length of side of square: ";
cin >> length;
area=length*length;
cout << "Area of square is: " << area;
};
int main()
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle"<<endl<<" [Link]"<<endl<<"3. Square"<<endl;
int choice;
cin >> choice;
switch (choice)
case 1:{
Rectangle rec;
break;
case 2:{
Circle cir;
break;
case 3:{
Square sqr;
break;
default:{
cout << "try again: your choice is invalid";
break;
return 0;
}
Task 01: Class Definition and Implementation
Create a class called MotorVehicle that represents a motor vehicle using: make (type string), fuelType
(type string), yearOfManufacture (type int), color (type string) and engineCapacity (type int). Your
class should have a constructor that initializes the three data members. Provide a set and a get function
for each data member. Add a member function called displayCarDetails that displays the five data
members in five separate lines in the form "member name: member value". Write a test program to
demonstrate MotorVehicle’s capabilities, that takes required values as input from the user.
#include <iostream>
#include <string>
using namespace std;
class MotorVehicle
private:
string make;
string fuelType;
int yearOfManufacture;
string color;
int engineCapacity;
public:
MotorVehicle(const string& make, const string& fuelType, int year, const
string& color, int capacity)
this->make = make;
this->fuelType = fuelType;
this->color = color;
engineCapacity = capacity;
const string getMake() {
return make;
const string getFuelType() {
return fuelType;
const int getYearOfManufacture() {
return yearOfManufacture;
const string getColor() {
return color;
}
const int getEngineCapacity() {
return engineCapacity;
void setMake(const string& newMake) {
make = newMake;
void setFuelType(const string& newFuelType) {
fuelType = newFuelType;
void setYearOfManufacture(int newYear) {
yearOfManufacture = newYear;
void setColor(const string& newColor) {
color = newColor;
void setEngineCapacity(int newCapacity) {
engineCapacity = newCapacity;
void displayCarDetails() const {
cout << "Make: " << make << endl;
cout << "Fuel Type: " << fuelType << endl;
cout << "Year of Manufacture: " << yearOfManufacture << endl;
cout << "Color: " << color << endl;
cout << "Engine Capacity: " << engineCapacity << " cc" << endl;
};
int main()
string make, fuelType, color;
int year, engineCapacity;
cout << "Enter car details"<<endl;
cout << "Make: ";
cin >> make;
cout << "Fuel Type: ";
cin >> fuelType;
cout << "Year of Manufacture: ";
cin >> year;
cout << "Color: ";
cin >> color;
cout << "Engine Capacity : ";
cin >> engineCapacity;
MotorVehicle car(make, fuelType, year, color, engineCapacity);
cout << "\nCar Details:\n";
[Link]();
return 0;
Cricket team
#include <iostream>
using namespace std;
class Team
{
public:
Team()
{
score=0;
wickets=10;
}
Team(int initialScore, int initialWickets)
{
score=initialScore;
wickets=initialWickets;
}
void update(int runsScored, int wicketsLost)
{
score += runsScored;
wickets = max(wickets - wicketsLost, 0);
int getScore() const
{
return score;
}
int getWickets() const
{
return wickets;
}
int score;
int wickets;
};
int main()
{
Team team1, team2;
cout << "****Enter data for Team1****" << endl;
cout << "Enter score: ";
cin >> [Link];
cout << "Enter the number of wickets: ";
cin >> [Link];
cout << endl << "****Enter data for Team2****" << endl;
cout << "Enter score: ";
cin >> [Link];
cout << "Enter the number of wickets: ";
cin >> [Link];
Team team3(120, 3);
cout << endl << "**** Team1 created (default) ****"
<<endl;cout << "Team 1 has score: " << [Link]() << "
and the number of wickets: " << [Link]() << endl;
cout << endl << "**** Team2 created (default) ****" <<endl;
cout << "Team 2 has score: " << [Link]() << " and the
number of wickets: " << [Link]() << std::endl;
cout << endl << "**** Team3 created (parameterized) ****"
<<endl;
cout << "Team 3 has a score: " << [Link]() << " and
number of wickets: " << [Link]() << std::endl;
cout << endl << "** Team Scores and Wickets **" <<endl;
return 0;
}
Task 3: Constructor Implementation
Design a class of Circle with at least two data members: radius, originx, and originy. Origin is a
central point of a circle and radius is the distance between the central point and the boundary of a
circle. Since the origin is a point therefore it can be modeled with x and y coordinates.
(a). Write a program that finds the area, diameter, and circumference of a circle (create one sample
object and find the following) by creating an appropriate class. The area, circumference, and diameter
can be calculated using the following formulas, respectively:
Area=pie*radius*radius Circumference=2*pie*radius Diameter=radius/2
All the inputs should be taken from the user in the main function to set data members of the class (like
done in Task 1) and then relevant member functions of the class should be called get values and find
area, circumference, diameter. The functions for finding them must be a part of the class. Main
function should only call relevant methods.
(b) Create 4 circles and initialize them using the parameterized constructor (you can hardcode values
while calling the constructor). Find and display which of the circles are concentric. That is, circles
having the same central point (as shown below). (Hint: the logic for this will be implemented in
main())
(c) For the identified concentric circles, find the label for each circle. The label is the position number
(as shown above; the most internal circle has label 1, and so on... In the end, also display the labels
that you assigned. (Hint: the logic for this will be implemented in main())(d) Find and display: which of
the concentric circle has a diameter greater than 12. You must
differentiate the relationship between the diameter and radius of any circle. (Hint: the logic for this
will be implemented in main())
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159;
class Circle {
public:
Circle() : radius(0.0), originX(0.0), originY(0.0) {}
Circle(double radius, double originX, double originY) {
if (radius < 0) {
cout << "Error: Radius cannot be negative." << endl;
radius = 0.0;
}
this->radius = radius;
this->originX = originX;
this->originY = originY;
double getArea() const { return PI * radius * radius; }
double getDiameter() const { return 2 * radius; }
double getCircumference() const { return 2 * PI * radius; }
void displayInfo() const {
cout << "Radius: " << radius << endl;
cout << "Origin: (" << originX << ", " << originY << ")" << endl;
double radius;
double originX;
double originY;
};
int main() {
Circle circles[4];
circles[0] = Circle(5.0, 1.0, 2.0);
circles[1] = Circle(3.0, 1.0, 2.0);
circles[2] = Circle(7.0, 4.0, 3.0);
circles[3] = Circle(10.0, 1.0, 2.0);
circle2
bool areConcentric = false;
for (int i = 1; i < 4; i++) {
if (circles[0].originX == circles[i].originX && circles[0].originY ==
circles[i].originY) {
areConcentric = true;
cout << "Circles " << 1 << " and " << i + 1 << " are concentric."
<< endl;
if (!areConcentric) {
cout << "No concentric circles found." << endl;
int label = 1;
if (areConcentric) {
circles[0].displayInfo();
cout << "Label: " << label << endl << endl;
label++;
for (int i = 1; i < 4; i++) {
if (circles[0].originX == circles[i].originX && circles[0].originY
== circles[i].originY) {
circles[i].displayInfo();
cout << "Label: " << label << endl << endl;
label++;
for (int i = 0; i < 4; i++) {
if (circles[i].getDiameter() > 12) {
cout << "Circle with label " << (i == 0 ? 1 : label - 1) << " has
diameter greater than 12." << endl;
return 0;
Task 4: Constructor Implementation
Consider a class named Job that has a deadline as a data member and relevant getter/setter
method(s). Assume you have to schedule two earliest jobs on the basis of their deadlines. That is, if
there are three jobs in the system with deadlines (deadline1, deadline2, and deadline3, respectively)
then the system should report the top two earliest jobs (with the smallest deadline value). You might
need to find the deadline with the smallest and second smallest value.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Job {
private:
int deadline;
public:
Job (int d)
deadline=d;
int getDeadline() const
{
return deadline;
};
bool compareJobs(const Job& job1, const Job& job2)
return [Link]() < [Link]();
int main() {
std::vector<Job> jobs;
jobs.push_back(Job(5));
jobs.push_back(Job(3));
jobs.push_back(Job(7));
sort([Link](), [Link](), compareJobs);
cout << "Two earliest jobs:"<<endl;
for (int i = 0; i < 2; ++i)
cout << "Job " << i + 1 << " - Deadline: " <<jobs[i].getDeadline() << endl;
return 0;
}
Task 01: String Formatting [Estimated 40 minutes / 30 marks]
Part (a):
Define a class called StringFormatter. The purpose of an object of this class is to store a string
variable (you may use the C++ string type or a char array). An object of this class can be created by
calling a constructor that accepts a one-string argument. The string to be passed as argument will be a
long line of text, such as
“The world is indeed full of peril and in it, there are many dark places. But still, there is much that is
fair. And though in all lands, love is now mingled with grief, it still grows, perhaps, the greater.”
The object will also have a function called printRightAligned() which accepts one integer argument n.
The value of the argument represents the maximum number of characters that can be displayed on a
line. This function displays the string stored in the object’s attribute on the screen, right aligned and
with no more than n characters per line. Similarly, there should be a function called
printLeftAlgigned() which displays the text left aligned, again, with no more than n characters per
line.
For printRightAligned(), you can assume that the display is 20 characters wide, i.e, if a line to be
displayed contains 15 characters, you would display 5 spaces followed by the text.
Note: You are not allowed to use iomanip or any other library except string.
#include <iostream>
#include <string>
using namespace std;
class StringFormatter {
private:
string text;
public:
// Constructor with simple initialization
StringFormatter(const string& input_text) : text(input_text) {}
// Function to print the text right-aligned
void printRightAligned(int n) {
int length = [Link]();
int remaining = length;
int start = 0;
while (remaining > 0) {
int chars_to_print = min(n, remaining);
int spaces = n - chars_to_print;
// Print leading spaces
for (int i = 0; i < spaces; ++i)
cout << ' ';
// Print characters
cout << [Link](start, chars_to_print) << endl;
remaining -= chars_to_print;
start += chars_to_print;
}
// Function to print the text left-aligned
void printLeftAligned(int n) {
int length = [Link]();
int remaining = length;
int start = 0;
while (remaining > 0) {
int chars_to_print = min(n, remaining);
// Print characters
cout << [Link](start, chars_to_print) << endl;
remaining -= chars_to_print;
start += chars_to_print;
};
int main() {
string input_text = "The world is indeed full of peril and in it, there are many
dark places. But still, there is much that is fair. And though in all lands, love is now
mingled with grief, it still grows, perhaps, the greater.";
StringFormatter formatter(input_text);
cout << "Right Aligned:" << endl;
[Link](20);
cout << "\nLeft Aligned:" << endl;
[Link](20);
return 0;