0% found this document useful (0 votes)
30 views33 pages

LAB 1, 2, 6 Solution (Fellow)

Uploaded by

ayeshagull26june
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)
30 views33 pages

LAB 1, 2, 6 Solution (Fellow)

Uploaded by

ayeshagull26june
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/ 33

LAB 1

Task 01: First C++ Program


Write a C++ program which:
• Displays “This is my first C++ program” on the Console

#include <iostream>
using namespace std;
int main()
{
cout << "This is my First Program" << endl;

return 0;
}

Task 02: Middle Number [Estimated 10 minutes / 10 marks]


Write a C++ program which:
• Declares three integers
• Read the integers from the user
• Displays the integer which is neither the smallest nor the largest among the three on the Console
Note: if statement is same as used in C language.
Input Output
234 Middle number is: 3
2 5 -1 Middle number is: 2

#include <iostream>
using namespace std;
int main()
{
int n1,n2,n3;
cout << "Enter Three Numbers: ";
cin >> n1 >> n2 >> n3;
cout << "The middle number is: " << n2 << endl;

return 0;
}

Task 01: Iterate String


Write a C++ program that:
• Inputs a string from user
• Count the number of words and spaces in the strings
• Display the count on Console
Input Output
This is a string. Words: 4Spaces: 3
String Words: 1 Spaces: 0
#include <iostream>
#include <string>
using namespace std;

int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);

int wordCount = 0;
int spaceCount = 0;

for (char ch : str) {


if (ch == ' ') {
spaceCount++;
} else if (isalpha(ch)) {
wordCount++;
}
}

cout << "Words: " << wordCount << endl;


cout << "Spaces: " << spaceCount << endl;

return 0;
}

Task 02: Palindrome


Create a C++ program that
• Inputs a string from user
• Check if string is Palindrome or not
• Display the result on the Console
Input Output
101 Palindrome
100 Not a Palindrome
1 Palindrome

#include <iostream>

using namespace std;

bool is_palindrome(int x) {
if (x < 0) {
return false;
}

int original_x = x;
int reversed_x = 0;
while (original_x > 0) {
reversed_x = reversed_x * 10 + original_x % 10;
original_x /= 10;
}

return x == reversed_x;
}

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

if (is_palindrome(num)) {
cout << num << " is a palindrome." << endl;
} else {
cout << num << " is not a palindrome." << endl;
}

return 0;
}

Task 03: Geometry


Create a C++ Program that:
• Creates a Class Geometry with data members
o Length
o Width
• Create an object of above Class
• Ask user to Input the Length and Width
• Check if length and width are equal
• Display “Square” on the Console if they are equal otherwise display “Rectangle”
Input Output
Length: 10Width: 10 Square
Length:10Width: 5 Rectangle

#include <iostream>
using namespace std;

class Geometry{
public:
float length;
float width;
Geometry(){
cout << "Enter length of shape: ";
cin >> length;
cout << "Enter Width of the shape: ";
cin >> width;
if (length == width){
cout << "\nShape is square.\n";
}
else{
cout << "Shape is rectangle.";
}
}
};
int main()
{
Geometry geo;
return 0;
}

Task 04: Find and Correct the error


Find and correct the errors from the following code:

CORRECTED CODE

#include <iostream>
#include <string>
using namespace std;

class Student{
public:
string name;
string rollno;
string subjects[5];
void display(){
cout << name << '\n';
cout << rollno << '\n';
for (size_t i = 0; i < 5; i++)
{
cout << subjects[i] << endl;
}
cout << endl;
}
};
int main(){

Student std1, std2;


std1.name = "Name";
std1.rollno = "Roll Number";
for (size_t i = 0; i < 5; i++)
{
std1.subjects[i] = "subject " + to_string(i+1);
}

std2.name = std1.name;
std2.rollno = std1.rollno;
for (size_t i = 0; i < 5; i++)
{
std2.subjects[i] = std1.subjects[i];
}

std1.display();
std2.display();

return 0;
}

Task 01: Cars


Create a C++ program that:
• Makes a car Class with data members:
o wheels
o doors
o currentSpeed
• And with Class Methods
o speed (Inside Class)
o break (Outside Class)
• Make two objects in the name of ferrari and mustang.
• Every time when you call speed function currentSpeed is increased by 5 while break function
decrease it by 5.

#include <iostream>
using namespace std;

class Car {
private:
int wheels;
int doors;
int currentSpeed;

public:
// Constructor to initialize data members
Car(int numWheels, int numDoors) {
wheels = numWheels;
doors = numDoors;
currentSpeed = 0; // Initial speed is 0
}

// Method to increase speed (inside class)


void speedUp() {
currentSpeed += 5;
}

// Method to decrease speed (outside class)


void applyBrake() {
currentSpeed -= 5;
}

// Method to display car details


void displayDetails() {
cout << "Car details:\n";
cout << "Wheels: " << wheels << endl;
cout << "Doors: " << doors << endl;
cout << "Current Speed: " << currentSpeed << " km/h" << endl;
}
};

int main() {
// Create two car objects
Car ferrari(4, 2); // Ferrari with 4 wheels and 2 doors
Car mustang(4, 4); // Mustang with 4 wheels and 4 doors
// Accelerate Ferrari
ferrari.speedUp();
ferrari.speedUp();
ferrari.speedUp();

// Apply brake to Mustang


mustang.applyBrake();

// Display car details


ferrari.displayDetails();
mustang.displayDetails();

return 0;
}

LAB 2
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:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
break;
}
}
return 0;
}
#include <iostream>
using namespace std;

class Rectangle{
public:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
break;
}
}
return 0;
}
#include <iostream>
using namespace std;

class Rectangle{
public:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
break;
}
}
return 0;
}
#include <iostream>
using namespace std;

class Rectangle{
public:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
break;
}
}
return 0;
}
#include <iostream>
using namespace std;

class Rectangle{
public:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
break;
}
}
return 0;
}
#include <iostream>
using namespace std;

class Rectangle{
public:
float height, width, area;
Rectangle(){
cout << "Enter Width and Height of rectangle: ";
cin >> width >> height;
cout << "\nYou chose rectangle.\n";
cout << "The area of Rectangle is: " << (width * height);
}
};
class Circle{
public:
float radius;
Circle(){
cout << "Enter the radius of circle: ";
cin >> radius;
cout << "\nYou chose circle.\n";
cout << "Area of circle is: " << (3.14759 * radius * radius);
}
};
class Square{
public:
float side;
Square(){
cout << "Enter the length of side of square: ";
cin >> side;
cout << "\nYou chose square\n";
cout << "Area of square is: " << (side*side);
}
};
int main()
{
int choice;
cout << "Choose the shape to calculate the area:\n";
cout << "1. Rectangle\n2. Circle\n3. Square\n";
cin >> choice;
switch (choice)
{
case 1:{
Rectangle rect;
break;
}
case 2:{
Circle circle;
break;
}
case 3:{
Square square;
break;
}
default:{
cout << "Please Enter a valid choice.";
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:
// Constructor to initialize data members
MotorVehicle(const string& make, const string& fuelType, int year, const
string& color, int capacity) {
this->make = make;
this->fuelType = fuelType;
yearOfManufacture = year;
this->color = color;
engineCapacity = capacity;
}

// Getter functions
string getMake() const {
return make;
}

string getFuelType() const {


return fuelType;
}

int getYearOfManufacture() const {


return yearOfManufacture;
}

string getColor() const {


return color;
}

int getEngineCapacity() const {


return engineCapacity;
}

// Setter functions
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;
}

// Display car details


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:\n";


cout << "Make: ";
cin >> make;
cout << "Fuel Type: ";
cin >> fuelType;
cout << "Year of Manufacture: ";
cin >> year;
cout << "Color: ";
cin >> color;
cout << "Engine Capacity (cc): ";
cin >> engineCapacity;

MotorVehicle car(make, fuelType, year, color, engineCapacity);


cout << "\nCar Details:\n";
car.displayCarDetails();

return 0;
}

Assume you have to write a program for a cricket game. There are two teams and each team has a
value for score and number of wickets. You are required to design a class Team that has relevant
member functions for setting the score and wicket’s value and for getting these values too.
(a). The score and wicket of both the teams should be taken as an input from the user in main(). The
main function should interact with the class Team to set and get values. Write a function in the class
Team to update the score and wickets of a particular team.
Expected output (console):
****Enter data for Team1****
Enter score: 24
Enter the number of wickets: 4
Team 1 has score: 24 and number of wickets: 4
****Enter data for Team2****
Enter score: 67
Enter the number of wickets: 9
Team 1 has score: 67 and number of wickets: 9
Main function (driver function) should do the following tasks:
//declare objects to interact with the class //take input from user
//call set methods of class
//call getter methods and print to the console
(b). Declare two more objects and initialize one of the objects using the default constructor and the
other using a parameterized constructor. You may send hardcoded values while calling the
parametrized constructor.
Expected output (console):
**** Team3 created (default)****
Team 3 has score: 0 and number of wickets: 10
**** Team4 created (parameterized)****
Team 4 has a score: 11 and number of wickets: 2
Main function (driver function) should do the following tasks:
//declare objects to interact with the class //call getter methods and print to the console
(c). In main(), write a logic that finds the team with 1) minimum score, 2) maximum score, and 3)
greater than 6 wickets. The main function should interact with the class Team to set and get values.
First, display the scores and wickets for all teams and then report 1,2, and 3.
Expected output (console):
Team 1 has score: 24 and the number of wickets: 4
Team 2 has score: 12 and the number of wickets: 9
Team 3 has score: 120 and the number of wickets: 3
Team 4 has score: 11 and number of wickets: 7 Team 3 has maximum score Team 4 has minimum
score Team 2 and 4 have greater than 6 wickets
Main function (driver function) should do the following tasks:
//continuing the existing program…
//display values for teams using getter methods //find maximum etc..as asked

#include <iostream>

class Team {
public:
// Default constructor with reasonable initial values
Team() : score(0), wickets(10) {}

// Parameterized constructor for more control


Team(int initialScore, int initialWickets) : score(initialScore),
wickets(initialWickets) {}

// Update score and wickets (consider boundary conditions)


void update(int runsScored, int wicketsLost) {
score += runsScored;
wickets = std::max(wickets - wicketsLost, 0); // Ensure wickets don't
go negative
}

// Getters for score and wickets


int getScore() const { return score; }
int getWickets() const { return wickets; }

private:
int score;
int wickets;
};

int main() {
Team team1, team2; // Objects using default constructor

std::cout << "****Enter data for Team1****" << std::endl;


std::cout << "Enter score: ";
std::cin >> team1.score;
std::cout << "Enter the number of wickets: ";
std::cin >> team1.wickets;

std::cout << std::endl << "****Enter data for Team2****" << std::endl;
std::cout << "Enter score: ";
std::cin >> team2.score;
std::cout << "Enter the number of wickets: ";
std::cin >> team2.wickets;

Team team3(120, 3); // Object using parameterized constructor

std::cout << std::endl << "**** Team1 created (default) ****" <<
std::endl;
std::cout << "Team 1 has score: " << team1.getScore() << " and the number
of wickets: " << team1.getWickets() << std::endl;

std::cout << std::endl << "**** Team2 created (default) ****" <<
std::endl;
std::cout << "Team 2 has score: " << team2.getScore() << " and the number
of wickets: " << team2.getWickets() << std::endl;

std::cout << std::endl << "**** Team3 created (parameterized) ****" <<
std::endl;
std::cout << "Team 3 has a score: " << team3.getScore() << " and number of
wickets: " << team3.getWickets() << std::endl;

std::cout << std::endl << "** Team Scores and Wickets **" << std::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; // Define PI constant

class Circle {
public:
// Default constructor with origin at (0, 0) and radius 0
Circle() : radius(0.0), originX(0.0), originY(0.0) {}

// Parameterized constructor for flexible initialization with error


handling
Circle(double radius, double originX, double originY) {
if (radius < 0) {
cerr << "Error: Radius cannot be negative." << endl;
radius = 0.0; // Set radius to a valid default value
}
this->radius = radius;
this->originX = originX;
this->originY = originY;
}

// Member functions to calculate and return area, diameter, and


circumference
double getArea() const { return PI * radius * radius; }
double getDiameter() const { return 2 * radius; }
double getCircumference() const { return 2 * PI * radius; }

// Display circle information for readability


void displayInfo() const {
cout << "Radius: " << radius << endl;
cout << "Origin: (" << originX << ", " << originY << ")" << endl;
}
double radius;
double originX;
double originY;
};

int main() {
// Create 4 circles with hardcoded values for part (b)
Circle circles[4];
circles[0] = Circle(5.0, 1.0, 2.0);
circles[1] = Circle(3.0, 1.0, 2.0); // Concentric with circle1
circles[2] = Circle(7.0, 4.0, 3.0);
circles[3] = Circle(10.0, 1.0, 2.0); // Concentric with circle1 and
circle2

bool areConcentric = false; // Flag to track concentricity

// Find concentric circles (part (b))


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;
}

// Assign labels for concentric circles (part (c))


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++;
}
}
}

// Find circle with diameter greater than 12 (part (d))


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> // For sorting

class Job {
private:
int deadline;

public:
// Constructor to initialize the deadline
Job(int d) : deadline(d) {}

// Getter for the deadline


int getDeadline() const {
return deadline;
}
};

// Comparator function to sort jobs based on deadlines


bool compareJobs(const Job& job1, const Job& job2) {
return job1.getDeadline() < job2.getDeadline();
}

int main() {
// Create some sample jobs with deadlines
std::vector<Job> jobs;
jobs.push_back(Job(5)); // Job 1
jobs.push_back(Job(3)); // Job 2
jobs.push_back(Job(7)); // Job 3

// Sort the jobs based on deadlines


std::sort(jobs.begin(), jobs.end(), compareJobs);

// Display the two earliest jobs


std::cout << "Two earliest jobs:\n";
for (int i = 0; i < 2; ++i) {
std::cout << "Job " << i + 1 << " - Deadline: " <<
jobs[i].getDeadline() << std::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>

class StringFormatter {
public:
StringFormatter(const std::string& text) : text_(text) {}

void printRightAligned(int lineLength) {


int currentLineLength = 0;
for (int i = 0; i < text_.length(); i++) {
if (currentLineLength + 1 > lineLength) {
std::cout << std::endl;
currentLineLength = 0;
}
std::cout << " "; // Right-align with a leading space
currentLineLength++;
std::cout << text_[i];
}
std::cout << std::endl;
}

void printLeftAligned(int lineLength) {


std::string::size_type currentPosition = 0;
while (currentPosition < text_.length()) {
std::string::size_type nextLineBreak = text_.find_first_of(" ",
currentPosition + lineLength);
if (nextLineBreak == std::string::npos) {
nextLineBreak = text_.length();
}
std::cout << text_.substr(currentPosition, nextLineBreak -
currentPosition) << std::endl;
currentPosition = nextLineBreak + 1; // Skip the space
}
}

private:
std::string text_;
};
int main() {
std::string longText = "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(longText);

std::cout << "Right-aligned (line length 20):\n";


formatter.printRightAligned(20);

std::cout << "\nLeft-aligned (line length 30):\n";


formatter.printLeftAligned(30);

return 0;
}

LAB 6
Task 01 Part(a): Shallow Copy • Create a class
"Rectangle" with the following attributes:
o Length (int)
o Width (int)
• Implement a copy constructor for the "Rectangle" class. The copy constructor should create a new
object that is a copy of an existing "Rectangle" object.
• In the main function, create a "Rectangle" object and initialize it with a length and width of your
choice.
• Create a second "Rectangle" object that is a copy of the first object using the copy constructor.
• Verify that the copy constructor correctly created a new object with the same length and width as
the original object.
• Modify the length or width of the second rectangle and verify that the changes affect both the
Rectangles
#include <iostream>

class Rectangle {
public:
int length;
int width;

// Constructor
Rectangle(int l, int w) : length(l), width(w) {}

// Copy constructor
Rectangle(const Rectangle& other) : length(other.length),
width(other.width) {}
};

int main() {
// Create the original Rectangle
Rectangle originalRectangle(10, 5);

// Create a copy using the copy constructor


Rectangle copiedRectangle = originalRectangle;

// Verify that the copy constructor correctly created a new object


std::cout << "Original Rectangle: Length = " << originalRectangle.length
<< ", Width = " << originalRectangle.width << std::endl;
std::cout << "Copied Rectangle: Length = " << copiedRectangle.length
<< ", Width = " << copiedRectangle.width << std::endl;

// Modify the length of the second rectangle


copiedRectangle.length = 15;

// Verify that changes affect both rectangles


std::cout << "Modified Copied Rectangle: Length = " <<
copiedRectangle.length
<< ", Width = " << copiedRectangle.width << std::endl;

return 0;
}

Task 01 Part(b): Deep Copy


• Create a class "Rectangle" with the following attributes:
o Length (int)
o Width (int)
• Implement a copy constructor for the "Rectangle" class. The copy constructor should create a new
object that is a copy of an existing "Rectangle" object
• In the main function, create a "Rectangle" object and initialize it with a length and width of your
choice
• Create a second "Rectangle" object that is a copy of the first object using the copy constructor
• Verify that the copy constructor correctly created a new object with the same length and width as
the original object
• Modify the length or width of the second rectangle and verify that the changes only affect the
second rectangle not the original one

#include <iostream>

class Rectangle {
public:
int length;
int width;

// Constructor
Rectangle(int l, int w) : length(l), width(w) {}

// Deep copy constructor


Rectangle(const Rectangle& other) : length(other.length),
width(other.width) {}

// Function to display rectangle details


void display() {
std::cout << "Length: " << length << ", Width: " << width <<
std::endl;
}
};

int main() {
// Create the original Rectangle
Rectangle originalRectangle(10, 5);

// Create a copy using the deep copy constructor


Rectangle copiedRectangle = originalRectangle;

// Verify that the deep copy constructor correctly created a new object
std::cout << "Original Rectangle: ";
originalRectangle.display();
std::cout << "Copied Rectangle: ";
copiedRectangle.display();

// Modify the length of the second rectangle


copiedRectangle.length = 15;

// Verify that changes only affect the second rectangle


std::cout << "Modified Copied Rectangle: ";
copiedRectangle.display();
std::cout << "Original Rectangle (unchanged): ";
originalRectangle.display();
return 0;
}

Task 01: Copy Students • Create a class "Student"


with the following attributes:
o Name (string)
o Roll number (int)
o Age (int)
• Implement the copy constructor for the "Student" class. The copy constructor should create a new
object that is a copy of an existing "Student" object.
• In main, create a vector of "Student" objects and initialize it with a few student records.
• Create a function that takes a vector of "Student" objects as an argument and prints the details of
each student in the vector.
• Create a new vector that is a copy of the original vector using the copy constructor.
• Verify that the copy constructor correctly created a new vector with a copy of each student record.
• Modify one of the student records in the new vector and verify that the changes only affect the new
vector and not the original vector.

#include <iostream>
#include <vector>
#include <string>

class Student {
public:
std::string name;
int rollNumber;
int age;

// Constructor
Student(const std::string& n, int roll, int a) : name(n),
rollNumber(roll), age(a) {}

// Copy constructor
Student(const Student& other) : name(other.name),
rollNumber(other.rollNumber), age(other.age) {}

// Display student details


void display() const {
std::cout << "Name: " << name << ", Roll Number: " << rollNumber << ",
Age: " << age << std::endl;
}
};

// Function to print student details from a vector


void printStudentDetails(const std::vector<Student>& students) {
for (const auto& student : students) {
student.display();
}
}

int main() {
// Create a vector of Student objects
std::vector<Student> originalStudents;
originalStudents.push_back(Student("Alice", 101, 20));
originalStudents.push_back(Student("Bob", 102, 21));
originalStudents.push_back(Student("Charlie", 103, 19));

// Print original student details


std::cout << "Original Student Details:" << std::endl;
printStudentDetails(originalStudents);

// Create a new vector by copying the original vector


std::vector<Student> copiedStudents = originalStudents;

// Modify one student record in the new vector


copiedStudents[1].name = "Updated Bob";

// Verify that changes only affect the new vector


std::cout << "\nModified Student Details (Copied Vector):" << std::endl;
printStudentDetails(copiedStudents);

std::cout << "\nOriginal Student Details (Unchanged):" << std::endl;


printStudentDetails(originalStudents);

return 0;
}

Task 02: Complex Numbers


• Write a program to make a class of Complex numbers with data members and member
functions:
o real number
o imaginary number
o getreal() to get real numbers
o getimg() to get imaginary numbers
o show() to show data
o operator+() "subtract two objects"
o operator-() "add two objects"
o operator/()"multiply two objects"
o operator*() "divide first object by second object".
• Also write a driver code to test the above functionalities

#include <iostream>

class ComplexNumber {
private:
double real;
double imaginary;

public:
// Constructor
ComplexNumber(double r, double i) : real(r), imaginary(i) {}

// Getter methods
double getReal() const {
return real;
}

double getImaginary() const {


return imaginary;
}

// Display complex number


void show() const {
std::cout << real << " + " << imaginary << "i" << std::endl;
}

// Operator overloads
ComplexNumber operator+(const ComplexNumber& other) const {
return ComplexNumber(real + other.real, imaginary + other.imaginary);
}

ComplexNumber operator-(const ComplexNumber& other) const {


return ComplexNumber(real - other.real, imaginary - other.imaginary);
}

ComplexNumber operator*(const ComplexNumber& other) const {


double newReal = real * other.real - imaginary * other.imaginary;
double newImaginary = real * other.imaginary + imaginary * other.real;
return ComplexNumber(newReal, newImaginary);
}

ComplexNumber operator/(const ComplexNumber& other) const {


double denominator = other.real * other.real + other.imaginary *
other.imaginary;
double newReal = (real * other.real + imaginary * other.imaginary) /
denominator;
double newImaginary = (imaginary * other.real - real *
other.imaginary) / denominator;
return ComplexNumber(newReal, newImaginary);
}
};

int main() {
// Create complex numbers
ComplexNumber num1(3.0, 2.0);
ComplexNumber num2(1.5, 4.0);

// Test operator overloads


ComplexNumber sum = num1 + num2;
ComplexNumber difference = num1 - num2;
ComplexNumber product = num1 * num2;
ComplexNumber quotient = num1 / num2;

// Display results
std::cout << "Complex Number 1: ";
num1.show();
std::cout << "Complex Number 2: ";
num2.show();

std::cout << "Sum: ";


sum.show();
std::cout << "Difference: ";
difference.show();
std::cout << "Product: ";
product.show();
std::cout << "Quotient: ";
quotient.show();

return 0;
}

Task 03: Matrix Operations


• Create a class Matrix to represent matrices. The class should have two data members:
o row to represent the number of rows
o col to represent the number of columns
o A dynamic 2-D array mat to store the elements of the matrix.
• Overload the following binary operators for the Matrix class:
o + operator to add two matrices
o - operator to subtract two matrices
o * operator to multiply two matrices

#include <iostream>
#include <vector>

class Matrix {
private:
int row;
int col;
std::vector<std::vector<int>> mat;
public:
// Constructor
Matrix(int r, int c) : row(r), col(c) {
mat.resize(row, std::vector<int>(col, 0));
}

// Set matrix elements


void setElement(int i, int j, int value) {
if (i >= 0 && i < row && j >= 0 && j < col) {
mat[i][j] = value;
}
}

// Display matrix
void display() const {
for (const auto& rowVec : mat) {
for (int val : rowVec) {
std::cout << val << " ";
}
std::cout << std::endl;
}
}

// Overload + operator for matrix addition


Matrix operator+(const Matrix& other) const {
if (row != other.row || col != other.col) {
std::cerr << "Matrix dimensions do not match for addition!" <<
std::endl;
return Matrix(0, 0);
}

Matrix result(row, col);


for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
result.mat[i][j] = mat[i][j] + other.mat[i][j];
}
}
return result;
}

// Overload - operator for matrix subtraction


Matrix operator-(const Matrix& other) const {
if (row != other.row || col != other.col) {
std::cerr << "Matrix dimensions do not match for subtraction!" <<
std::endl;
return Matrix(0, 0);
}
Matrix result(row, col);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
result.mat[i][j] = mat[i][j] - other.mat[i][j];
}
}
return result;
}

// Overload * operator for matrix multiplication


Matrix operator*(const Matrix& other) const {
if (col != other.row) {
std::cerr << "Matrix dimensions do not match for multiplication!"
<< std::endl;
return Matrix(0, 0);
}

Matrix result(row, other.col);


for (int i = 0; i < row; ++i) {
for (int j = 0; j < other.col; ++j) {
for (int k = 0; k < col; ++k) {
result.mat[i][j] += mat[i][k] * other.mat[k][j];
}
}
}
return result;
}
};

int main() {
// Example usage
Matrix A(2, 3);
A.setElement(0, 0, 1);
A.setElement(0, 1, 2);
A.setElement(0, 2, 3);
A.setElement(1, 0, 4);
A.setElement(1, 1, 5);
A.setElement(1, 2, 6);

Matrix B(2, 3);


B.setElement(0, 0, 7);
B.setElement(0, 1, 8);
B.setElement(0, 2, 9);
B.setElement(1, 0, 10);
B.setElement(1, 1, 11);
B.setElement(1, 2, 12);
Matrix C = A + B;
Matrix D = A - B;
Matrix E = A * B;

std::cout << "Matrix A:" << std::endl;


A.display();
std::cout << "Matrix B:" << std::endl;
B.display();
std::cout << "Matrix A + B:" << std::endl;
C.display();
std::cout << "Matrix A - B:" << std::endl;
D.display();
std::cout << "Matrix A * B:" << std::endl;
E.display();

return 0;
}

You might also like