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

Sree Muthukumaraswamy College: Department of Bca Object Oriented Programming Using C++ Lab

The program creates a Point class to represent 2D points with methods to set and get point values, calculate the distance between two points, and check if two points are equal. It initializes points, displays their values, and finds the distance between them.

Uploaded by

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

Sree Muthukumaraswamy College: Department of Bca Object Oriented Programming Using C++ Lab

The program creates a Point class to represent 2D points with methods to set and get point values, calculate the distance between two points, and check if two points are equal. It initializes points, displays their values, and finds the distance between them.

Uploaded by

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

SREE MUTHUKUMARASWAMY

COLLEGE
92 / 1 & 9, Muthamizh Nagar, Kodungaiyur, Chennai – 118.

I BCA (COMPUTER APPLICATIONS)

DEPARTMENT OF BCA

OBJECT ORIENTED PROGRAMMING USING C++ LAB

Name of Student :

Batch Number :

University Register No. :


SREE MUTHUKUMARASWAMY
COLLEGE
92 / 1 & 9, Muthamizh Nagar, Kodungaiyur, Chennai – 118.

I BCA (COMPUTER APPLICATIONS)

DEPARTMENT OF BCA

OBJECT ORIENTED PROGRAMMING USING C++ LAB

Name of Student :

Batch Number :

University Register No. :

Certified to be bonafide record of works done in the computer lab.

Head of the Department Staff-in-Charge

Submitted for the Practical Examination held in the year 2024 on at


Sree Muthukumaraswamy College, Chennai.

Internal Examiner External Examiner


INDEX

PAGE
S.NO DATE TITLE SIGN
NO
A class to represent a complex number which has
member functions.
1 a. Set and show the value of the complex number
b. Add, subtract and multiply two complex numbers
c. Multiplying the complex number with a scalar value
A Point class that represents a 2-d point in a plane
a. Set and show the value of a point
2 b. Find the distance between two points
c. Check whether two points are equal or not
A class that represents a Harmonic Progression (HP).
a.Generate the HP up to a specified number of terms
b. Calculate the sum of the HP to n terms and to
3 infinity
c. Generate the nth term of the HP
d. Generate the corresponding Arithmetic Progression.

A class to represent a Solid object.


a. Apart from data members to represent dimensions,
4 use a data member to specify the type of solid.
b. Use functions to calculate volume and surface area
for different solids.
A class representing time in hh:mm:ss
a. Set and show the time
5 b. Find the difference between two time objects
c. Adding a given duration to a time
d. Conversion of the time object to seconds
Design A 3x3 matrix class For
a. Addition and multiplication of two matrices using
6 operator overloading
b. Maintaining a count of the number of matrix object
created

A class to represent a string using an array of size 100.


a. Copy Constructor
7 b. Concatenate two strings
c. Find the length of the string
d. Reversing a string e. Comparing two strings
A class to represent a string whose size is dynamically
8 allocated.
a. Copy Constructor
b. Destructor
c. Concatenate two strings
d. Find the length of the string
e. Reversing a string
f. Comparing two strings
A program using run-time polymorphism to compute
9 the area of the figures.

A function to sort the array elements to detect and


10 throw an exception for array-bound violations.

Demonstrate the use of the vector STL container.


11

Implement a telephone directory using files.


12
1. Write a class to represent a complex number which has member functions to
do the following

AIM:
The aim of this program is to create a class called ComplexNumber that represents a
complex number and provides functionalities to:
a. Set and show the value of the complex number.
b. Perform arithmetic operations such as addition, subtraction, and multiplication with other
complex numbers.
c. Multiply the complex number.

ALGORITHM:
STEP 1. Define a class ComplexNumber with attributes real and imaginary.
STEP 2. Implement _init_() method to initialize the complex number with real and imaginary
parts.
STEP 3. Implement set_value() method to set new values for the real and imaginary parts.
STEP 4. Implement show_value() method to display the complex number in the format a + bi.
STEP 5. Implement add(), subtract(), and multiply() methods to perform arithmetic operations
with other complex numbers.
STEP 6. Implement multiply_scalar() method.
a. Set and show the value of the complex number
PROGRAM:
#include <iostream>
class ComplexNumber {
private:
double real;
double imaginary;
public:
ComplexNumber(double r, double i) : real(r), imaginary(i) {}
void setValue(double r, double i) {
real = r;
imaginary = i;
}
void showValue() {
std::cout << "Complex Number: " << real << " + " << imaginary << "i" << std::endl;
}
};
int main() {
ComplexNumber complexNum(3.5, 2.0);
complexNum.showValue();
complexNum.setValue(1.0, -4.2);
complexNum.showValue();
return 0;
}

OUTPUT:

RESULT:

Thus, the above program executed successfully and output verified.


b. Add, subtract and multiply two complex numbers

PROGRAM:

#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
Complex() : real(0), imag(0) {}
void input() {
cout << "Enter real and imaginary parts: ";
cin >> real >> imag;
}
Complex add(const Complex& c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
Complex subtract(const Complex& c) {
Complex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
Complex multiply(const Complex& c) {
Complex temp;
temp.real = (real * c.real) - (imag * c.imag);
temp.imag = (real * c.imag) + (imag * c.real);
return temp;
}
void display() {
cout << "Result: " << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1, c2, result;
cout << "For the first complex number:\n";
c1.input();
cout << "\nFor the second complex number:\n";
c2.input();
result = c1.add(c2);
cout << "\nAddition: ";
result.display();
result = c1.subtract(c2);
cout << "Subtraction: ";
result.display();
result = c1.multiply(c2);
cout << "Multiplication: ";
result.display();
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
c. Multiplying the complex number with a scalar value

PROGRAM:

#include <iostream>
using namespace std;
class Complex {
private:
float real, imag;
public:
Complex() : real(0), imag(0) {}
void input() {
cout << "Enter real and imaginary parts: ";
cin >> real >> imag;
}
Complex multiplyByScalar(float scalar) {
Complex result;
result.real = real * scalar;
result.imag = imag * scalar;
return result;
}
void display() {
cout << "Result: " << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c;
float scalar;
cout << "Enter the complex number:\n";
c.input();
cout << "Enter the scalar value: ";
cin >> scalar;
// Multiplication by scalar
Complex result = c.multiplyByScalar(scalar);
cout << "Multiplication by scalar: ";
result.display();
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
2. Write a Point class that represents a 2-d point in a plane. Write member
functions to

AIM:
The aim of this program is to create a class called Point that represents a 2D point in a
plane and provides functionalities to:
a. Set and show the value of the point.
b. Find the distance between two points.
c. Check whether two points are equal or not.

ALGORITHM:
STEP 1. Define a class Point with attributes x and y to represent a 2D point in a plane.
STEP 2. Implement _init_() method to initialize the point with x and y coordinates.
STEP 3. Implement set_value() method to set new values for the x and y coordinates.
STEP 4. Implement show_value() method to display the coordinates of the point.
STEP 5. Implement distance() method to calculate the distance between two points using the
distance formula.
STEP 6. Implement equals() method to check whether two points are equal by comparing
their x and y coordinates
a. Set and show the value of a point

PROGRAM:

#include <iostream>
class Point {
private:
double x, y;
public:
// Constructor to initialize the Point object
Point() : x(0.0), y(0.0) {}

// Member function to set the values of the point


void setPoint(double newX, double newY) {
x = newX;
y = newY;
}

// Member function to display the values of the point


void showPoint() const {
std::cout << "Point coordinates: (" << x << ", " << y << ")\n";
}
};

int main() {
// Creating an instance of the Point class
Point myPoint;
// Setting the values of the point
myPoint.setPoint(3.5, 2.0);
// Displaying the values of the point
myPoint.showPoint();
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
b. Find the distance between two points

PROGRAM:
#include <iostream>
#include <cmath>
class Point {
private:
double x, y;
public:
// Constructor to initialize the Point object
Point() : x(0.0), y(0.0) {}

// Member function to set the values of the point


void setPoint(double newX, double newY) {
x = newX;
y = newY;
}

// Member function to display the values of the point


void showPoint() const {
std::cout << "Point coordinates: (" << x << ", " << y << ")\n";
}

// Member function to find the distance between two points


double distanceTo(const Point& otherPoint) const {
double dx = x - otherPoint.x;
double dy = y - otherPoint.y;
return std::sqrt(dx * dx + dy * dy);
}
};

int main() {
// Creating two instances of the Point class
Point point1, point2;

// Setting the values of the points


point1.setPoint(1.0, 2.0);
point2.setPoint(4.0, 6.0);

// Displaying the values of the points


point1.showPoint();
point2.showPoint();

// Finding the distance between the two points


double distance = point1.distanceTo(point2);
std::cout << "Distance between the two points: " << distance << std::endl;
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
c. Check whether two points are equal or not

PROGRAM:
#include <iostream>
class Point {
private:
double x, y;
public:
Point() : x(0.0), y(0.0) {}
void setPoint(double newX, double newY) {
x = newX;
y = newY;
}
void showPoint() const {
std::cout << "Point coordinates: (" << x << ", " << y << ")\n";
}
bool isEqual(const Point& otherPoint) const {
return (x == otherPoint.x) && (y == otherPoint.y);
}
};

int main() {
Point point1, point2, point3;
point1.setPoint(2.0, 3.0);
point2.setPoint(2.0, 3.0);
point3.setPoint(4.0, 6.0);
point1.showPoint();
point2.showPoint();
point3.showPoint();
if (point1.isEqual(point2)) {
std::cout << "point1 and point2 are equal.\n";
} else {
std::cout << "point1 and point2 are not equal.\n";
}
if (point1.isEqual(point3)) {
std::cout << "point1 and point3 are equal.\n";
} else {
std::cout << "point1 and point3 are not equal.\n";
}

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
3.Design and implement a class that represents a Harmonic Progression (HP).
Implement functions to do the following:

AIM:

The aim of this program is to create a class called HarmonicProgression that represents
Harmonic Progression (HP) and provides functionalities to:
a. Generate the HP up to a specified number of terms.
b. Calculate the sum of the HP up to n terms and to infinity.
c. Generate the nth term of the HP.
d. Generate the corresponding Arithmetic Progression (AP) using the facilities

ALGORITHM:

STEP1. Define a class SolidObject to represent a solid object with data members to specify the
type of solid and dimensions.
STEP 2. Implement _init_() method to initialize the solid object with the solid type and
dimensions.
STEP 3. Implement calculate_volume() method to calculate the volume of the solid object
based on its type and dimensions.
STEP 4. Implement calculate_surface_area() method to calculate the surface area of the solid
object based on its type and dimensions.
a. Generate the HP up to a specified number of terms

PROGRAM:

#include <iostream>
#include <vector>
class HarmonicProgression {
private:
double firstTerm;
double commonDifference;
public:
// Constructor to initialize the first term and common difference
HarmonicProgression(double first, double difference) : firstTerm(first),
commonDifference(difference) {}
// Function to generate the HP up to a specified number of terms
std::vector<double> generate(int numTerms) {
std::vector<double> hp;
double currentTerm = firstTerm;
for (int i = 0; i < numTerms; ++i) {
hp.push_back(currentTerm);
currentTerm += commonDifference;
}
return hp;
}
};

int main() {
// Creating an instance of the HarmonicProgression class
HarmonicProgression hp(1.0, 0.5); // Assuming a first term of 1.0 and a common
difference of 0.5
// Generating the HP up to a specified number of terms
int numTerms = 5;
std::vector<double> hpSequence = hp.generate(numTerms);
// Displaying the generated HP
std::cout << "Harmonic Progression up to " << numTerms << " terms:\n";
for (const auto& term : hpSequence) {
std::cout << term << " ";
}
std::cout << std::endl;
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
b. Calculate the sum of the HP to n terms and to infinity

PROGRAM:

#include <iostream>
class HarmonicProgression {
private:
double firstTerm;
double commonDifference;

public:
HarmonicProgression(double first, double difference) : firstTerm(first),
commonDifference(difference) {}
double sumUpToN(int n) {
double sum = 0;
double currentTerm = firstTerm;
for (int i = 0; i < n; ++i) {
sum += 1.0 / currentTerm;
currentTerm += commonDifference;
}
return sum;
}
double sumToInfinity() {
if (commonDifference != 0) {
std::cerr << "Error: The sum to infinity of this Harmonic Progression diverges." <<
std::endl;
return -1; // Return an error value
}
std::cerr << "Error: The sum to infinity of this Harmonic Progression is undefined
(common difference is zero)." << std::endl;
return -1; // Return an error value
}
};
int main() {
HarmonicProgression hp(1.0, 1.0);
int n = 5;
double sumUpToN = hp.sumUpToN(n);
std::cout << "Sum of the HP up to " << n << " terms: " << sumUpToN << std::endl;
double sumToInfinity = hp.sumToInfinity();
if (sumToInfinity != -1) {
std::cout << "Sum of the HP to infinity: " << sumToInfinity << std::endl;
}

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
c. Generate the nth term of the HP

PROGRAM:

#include <iostream>
class HarmonicProgression {
private:
double firstTerm;
double commonDifference;

public:
// Constructor to initialize the first term and common difference
HarmonicProgression(double first, double difference) : firstTerm(first),
commonDifference(difference) {}

// Function to generate the nth term of the HP


double nthTerm(int n) const {
return firstTerm + (n - 1) * commonDifference;
}
};

int main() {
// Creating an instance of the HarmonicProgression class
HarmonicProgression hp(1.0, 0.5); // Assuming a first term of 1.0 and a common
difference of 0.5

// Generating the 5th term of the HP


int nth = 5;
double term = hp.nthTerm(nth);

// Displaying the generated term


std::cout << "The " << nth << "th term of the Harmonic Progression: " << term <<
std::endl;

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
d. Generate the corresponding Arithmetic Progression. (Design and implement a
class that encapsulates an AP, and allow the HP class to use its facilities by
implementing friend functions.)

PROGRAM:

#include <iostream>
#include <vector>

class ArithmeticProgression; // Forward declaration

class HarmonicProgression {
private:
double firstTerm;
double commonDifference;

public:
// Constructor to initialize the first term and common difference
HarmonicProgression(double first, double difference) : firstTerm(first),
commonDifference(difference) {}

// Function to generate the HP up to a specified number of terms


std::vector<double> generate(int numTerms);

// Friend function declaration to access ArithmeticProgression class


friend std::vector<double> generateAP(const HarmonicProgression& hp, int numTerms);
};

class ArithmeticProgression {
private:
double firstTerm;
double commonDifference;

public:
// Constructor to initialize the first term and common difference
ArithmeticProgression(double first, double difference) : firstTerm(first),
commonDifference(difference) {}

// Function to generate the AP up to a specified number of terms


std::vector<double> generate(int numTerms);
};

// Function definition to generate the HP up to a specified number of terms


std::vector<double> HarmonicProgression::generate(int numTerms) {
std::vector<double> hp;
double currentTerm = firstTerm;

for (int i = 0; i < numTerms; ++i) {


hp.push_back(currentTerm);
currentTerm += commonDifference;
}

return hp;
}

// Friend function definition to access ArithmeticProgression class and generate the AP


std::vector<double> generateAP(const HarmonicProgression& hp, int numTerms) {
std::vector<double> ap;
double currentTerm = hp.firstTerm;
double commonDifference = hp.commonDifference;

for (int i = 0; i < numTerms; ++i) {


ap.push_back(currentTerm);
currentTerm += commonDifference;
}

return ap;
}
std::vector<double> ArithmeticProgression::generate(int numTerms) {
std::vector<double> ap;
double currentTerm = firstTerm;

for (int i = 0; i < numTerms; ++i) {


ap.push_back(currentTerm);
currentTerm += commonDifference;
}
return ap;
}
int main() {
HarmonicProgression hp(1.0, 0.5);
int numTerms = 5;
std::vector<double> hpSequence = hp.generate(numTerms);
std::cout << "Harmonic Progression up to " << numTerms << " terms:\n";
for (const auto& term : hpSequence) {
std::cout << term << " ";
}
std::cout << std::endl;
std::vector<double> apSequence = generateAP(hp, numTerms);
// Displaying the generated AP
std::cout << "Arithmetic Progression corresponding to the Harmonic Progression:\n";
for (const auto& term : apSequence) {
std::cout << term << " ";
}
std::cout << std::endl;

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
4. Design and implement a class to represent a Solid object.

AIM:

The aim of this program is to create a class called Solid Object that represents a solid
object.
This class will have data members to represent dimensions and specify the type of solid.
It will provide functions to calculate the volume and surface area for different types of solids.

ALGORITHM:

STEP 1. Define a class SolidObject to represent a solid object with data members to specify
the type of solid and dimensions.
STEP 2. Implement _init_() method to initialize the solid object with the solid type and
dimensions.
STEP 3. Implement calculate_volume() method to calculate the volume of the solid object
based on its type and dimensions.
STEP 4. Implement calculate_surface_area() method to calculate the surface area of the solid
object based on its type and dimensions.
a. Apart from data members to represent dimensions, use a data member to
specify the type of solid.

PROGRAM:

#include <iostream>
#include <string>
class SolidObject {
private:
double length;
double width;
double height;
std::string type;
public:
SolidObject(double len, double wid, double hei, const std::string& objType)
: length(len), width(wid), height(hei), type(objType) {}
void display() const {
std::cout << "Solid Type: " << type << std::endl;
std::cout << "Dimensions (length x width x height): " << length << " x " << width << "
x " << height << std::endl;
}
};
int main() {
SolidObject cube(5.0, 5.0, 5.0, "Cube");
cube.display();
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
b. Use functions to calculate volume and surface area for different solids

PROGRAM:
#include <iostream>
#include <cmath>
class Solid {
public:
static double cubeVolume(double sideLength) {
return sideLength * sideLength * sideLength;
}
static double cubeSurfaceArea(double sideLength) {
return 6 * sideLength * sideLength;
}
static double sphereVolume(double radius) {
return (4.0 / 3.0) * M_PI * radius * radius * radius;
}
static double sphereSurfaceArea(double radius) {
return 4 * M_PI * radius * radius;
}
static double cylinderVolume(double radius, double height) {
return M_PI * radius * radius * height;
}
static double cylinderSurfaceArea(double radius, double height) {
return 2 * M_PI * radius * (radius + height);
}
};
int main() {
double cubeSide = 3.0;
double sphereRadius = 2.5;
double cylinderRadius = 1.0;
double cylinderHeight = 4.0;
std::cout << "Cube with side length " << cubeSide << ":\n";
std::cout << "Volume: " << Solid::cubeVolume(cubeSide) << std::endl;
std::cout << "Surface Area: " << Solid::cubeSurfaceArea(cubeSide) << std::endl;
std::cout << "\nSphere with radius " << sphereRadius << ":\n";
std::cout << "Volume: " << Solid::sphereVolume(sphereRadius) << std::endl;
std::cout << "Surface Area: " << Solid::sphereSurfaceArea(sphereRadius) << std::endl;
std::cout << "\nCylinder with radius " << cylinderRadius << " and height " <<
cylinderHeight << ":\n";
std::cout << "Volume: " << Solid::cylinderVolume(cylinderRadius, cylinderHeight) <<
std::endl;
std::cout << "Surface Area: " << Solid::cylinderSurfaceArea(cylinderRadius,
cylinderHeight) << std::endl;

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
5. Design a class representing time in hh:mm:ss. Write functions to
AIM:

The aim of this program is to create a class called Time to represent time in hh:mm:ss
format.
This class provides the following functionalities:
a. set_time(): Set the time to the specified hours, minutes, and seconds.
b. show_time(): Display the time in hh:mm:ss format.
c. find_difference(): Find the difference between two Time objects and return the difference
as a new Time object.
d. add_duration(): Add a given duration (specified in hours, minutes, and seconds) to the time.
e. to_seconds(): Convert the time object to seconds.
ALGORITHM:

STEP 1. Define a class Time to represent time in hh:mm:ss format.


STEP 2. Implement _init_() method to initialize the time with hours, minutes, and seconds.
STEP 3. Implement set_time() method to set the time.
STEP 4. Implement show_time() method to display the time.
STEP 5. Implement find_difference() method to find the difference between two time objects.
STEP 6. Implement add_duration() method to add a given duration to the time.
STEP 7. Implement to_seconds() method to convert the time object to seconds.
a. Set and show the time

PROGRAM:
#include <iostream>
#include <iomanip>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {}
void setTime(int hh, int mm, int ss) {
if (hh >= 0 && hh < 24 && mm >= 0 && mm < 60 && ss >= 0 && ss < 60) {
hours = hh;
minutes = mm;
seconds = ss;
} else {
std::cerr << "Error: Invalid time values.\n";
}
}

// Member function to display the time


void showTime() const {
std::cout << std::setfill('0') << std::setw(2) << hours << ":"
<< std::setfill('0') << std::setw(2) << minutes << ":"
<< std::setfill('0') << std::setw(2) << seconds << std::endl;
}
};

int main() {
Time myTime;
myTime.setTime(12, 30, 45);
std::cout << "The current time is: ";
myTime.showTime();
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
b. Find the difference between two time objects

PROGRAM:

#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}
Time difference(const Time& otherTime) const {
int totalSeconds1 = hours * 3600 + minutes * 60 + seconds;
int totalSeconds2 = otherTime.hours * 3600 + otherTime.minutes * 60 +
otherTime.seconds;
int diffSeconds = std::abs(totalSeconds1 - totalSeconds2);
int diffHours = diffSeconds / 3600;
diffSeconds %= 3600;
int diffMinutes = diffSeconds / 60;
diffSeconds %= 60;
return Time(diffHours, diffMinutes, diffSeconds);
}
void displayTime() const {
std::cout << hours << ":" << minutes << ":" << seconds;
}
};
int main() {
Time time1(10, 30, 45);
Time time2(9, 15, 20);
Time timeDifference = time1.difference(time2);
std::cout << "Difference between ";
time1.displayTime();
std::cout << " and ";
time2.displayTime();
std::cout << " is ";
timeDifference.displayTime();
std::cout << std::endl;
return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
c. Adding a given duration to a time

PROGRAM:

#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;

public:
// Constructor to initialize time
Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}

// Function to add a given duration to a time


void addDuration(int h, int m, int s) {
seconds += s;
minutes += m + seconds / 60;
hours += h + minutes / 60;

seconds %= 60;
minutes %= 60;
hours %= 24;
}

// Function to display time


void display() const {
std::cout << "Time: " << hours << ":" << minutes << ":" << seconds << std::endl;
}
};

int main() {
// Creating an instance of the Time class
Time currentTime(10, 30, 45); // Example time: 10:30:45

// Adding a duration of 1 hour, 15 minutes, and 20 seconds


currentTime.addDuration(1, 15, 20);

// Displaying the updated time


currentTime.display();

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
d. Conversion of the time object to seconds

PROGRAM:

#include <iostream>
class Time {
private:
int hours;
int minutes;
int seconds;
public:
Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}
int toSeconds() const {
return hours * 3600 + minutes * 60 + seconds;}
void displayTime() const {
std::cout << "Time: " << hours << ":" << minutes << ":" << seconds << std::endl; }
};
int main() {
Time t(10, 30, 45); // Represents time 10:30:45
t.displayTime();
int totalSeconds = t.toSeconds();
std::cout << "Time in seconds: " << totalSeconds << std::endl;
return 0;
}
OUTPUT:

RESULT:

Thus, the above program executed successfully and output verified.


6. Design a 3x3 matrix class and demonstrate the following:

a. Addition and multiplication of two matrices using operator overloading


b. Maintaining a count of the number of matrix object created

AIM:

The aim of this program is to create a class called Matrix3x3 to represent a 3x3 matrix.
This class provides the following functionalities:
a. Overloading the addition and multiplication operators to perform matrix addition and
multiplication, respectively.
b. Maintaining a count of the number of matrix objects created using a class variable.

ALGORITHM:

STEP 1. Define a class Matrix3x3 to represent a 3x3 matrix.


STEP 2. Implement _init_() method to initialize the matrix with a 3x3 list.
STEP 3. Implement _add_() method to overload the addition operator for matrix addition.
STEP 4. Implement _mul_() method to overload the multiplication operator for matrix
multiplication.
STEP 5. Implement a class variable count to maintain the count of matrix objects created.
STEP 6. Implement a class method get_count() to get the count of matrix objects created.
PROGRAM:

#include<iostream>
class Matrix3x3 {
private:
int matrix[3][3];
static int objectCount;
public:
Matrix3x3() {
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
matrix[i][j] = 0;
++objectCount;
}
~Matrix3x3() {
--objectCount;
}
Matrix3x3 operator+(const Matrix3x3& other) const {
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
result.matrix[i][j] = matrix[i][j] + other.matrix[i][j];
return result;
}
Matrix3x3 operator*(const Matrix3x3& other) const {
Matrix3x3 result;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
for (int k = 0; k < 3; ++k)
result.matrix[i][j] += matrix[i][k] * other.matrix[k][j];
return result;
}
static int getObjectCount() {
return objectCount;
}
void display() const {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j)
std::cout << matrix[i][j] << " ";
std::cout << std::endl;
}
}
};

int Matrix3x3::objectCount = 0;
int main() {
Matrix3x3 matrix1, matrix2, resultMatrix;
resultMatrix = matrix1 + matrix2;
std::cout << "Matrix Addition Result:" << std::endl;
resultMatrix.display();
resultMatrix = matrix1 * matrix2;
std::cout << "Matrix Multiplication Result:" << std::endl;
resultMatrix.display();
std::cout << "Number of Matrix Objects Created: " << Matrix3x3::getObjectCount() <<
std::endl;
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
7. Design a class called cString to represent a string data type. Create a data
member in the class to represent a string using an array of size 100. Write the
following functionality as member functions: a. Copy Constructor
b. Concatenate two strings
c. Find the length of the string
d. Reversing a string
e. Comparing two strings

AIM:

The aim of this program is to create a class called cString to represent a string data type.
This class provides the following functionalities as member functions:
a. Copy Constructor: Create a new cString object by copying another cString.
b. Concatenate two strings: Concatenate the string represented by the object with another
string.
c. Find the length of the string: Return the length of the string represented by the object.
d. Reversing a string: Reverse the characters in the string represented by the object.
e. Comparing two strings: Compare the string represented by the object with another string.

ALGORITHM:

STEP1. Define a class cString to represent a string data type.


STEP 2. Implement _init_() method to initialize the string using an array of size 100.
STEP Implement copy_constructor() method to create a new cString object by copying another
cString.
STEP 4. Implement concatenate() method to concatenate two strings by appending the
characters of the second string to the first string.
STEP 5. Implement length() method to find the length of the string.
STEP 6. Implement reverse() method to reverse the characters in the string.
STEP 7. Implement compare() method to compare two strings lexicographically
PROGRAM:

#include<iostream>
#include<cstring>
class cString {
private:
char str[100]; // Fixed-size array to represent the string
public:
// Constructor
cString(const char* initialStr = "") {
strncpy(str, initialStr, sizeof(str) - 1);
str[sizeof(str) - 1] = '\0'; // Ensure null-termination
}
// Copy Constructor
cString(const cString& other) {
strncpy(str, other.str, sizeof(str));
}
// Concatenate two strings
cString concatenate(const cString& other) const {
cString result(str);
strncat(result.str, other.str, sizeof(result.str) - strlen(result.str) - 1);
return result;
}
// Find the length of the string
int length() const {
return strlen(str);
}
// Reversing a string
cString reverse() const {
cString reversed(str);
std::reverse(reversed.str, reversed.str + strlen(reversed.str));
return reversed;
}
// Comparing two strings
int compare(const cString& other) const {
return strcmp(str, other.str);
}
// Display the string
void display() const {
std::cout << str << std::endl;
}
};

int main() {
cString str1("Hello");
cString str2("World");
cString str3 = str1;
cString concatenated = str1.concatenate(str2);
std::cout << "Concatenated String: ";
concatenated.display();
std::cout << "Length of str1: " << str1.length() << std::endl;
cString reversed = str1.reverse();
std::cout << "Reversed String: ";
reversed.display();
int comparisonResult = str1.compare(str2);
std::cout << "Comparison Result: " << comparisonResult << std::endl;

return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
8. Design a class called cString to represent a string data type. Create a data
member in the class to represent a string whose size is dynamically allocated.
Write the following as member functions:
a. Copy Constructor
b. Destructor
c. Concatenate two strings
d. Find the length of the string
e. Reversing a string
f. Comparing two strings

AIM:

The aim of this program is to create a class called cString to represent a string data type.
This class provides the following functionalities as member functions:
a. Copy Constructor: Create a new cString object by copying another cString.
b. Destructor: Free the dynamically allocated memory.
c. Concatenate two strings: Concatenate the string represented by the object with another
string.
d. Find the length of the string: Return the length of the string represented by the object.
e. Reversing a string: Reverse the characters in the string represented by the object.
f. Comparing two strings: Compare the string represented by the object with another string.

ALGORITHM:

STEP1. Define a class cString to represent a string data type.


STEP 2. Implement _init_() method to initialize the string using a list.
STEP 3. Implement _del_() method as the destructor to free dynamically allocated memory.
STEP 4. Implement copy_constructor() method to create a new cString object by copying
another cString.
STEP 5. Implement concatenate() method to concatenate two strings by extending the list.
STEP 6. Implement length() method to find the length of the string by returning the length of
the list.
STEP 7. Implement reverse() method to reverse the characters in the string represented by the
object.
STEP 8. Implement compare() method to compare two strings by joining the characters in the
lists and comparing the resulting strings.
PROGRAM:
#include<iostream>
#include<cstring>
class cString {
private:
char* str; // Dynamic array to represent the string
public:
// Constructor
cString(const char* initialStr = nullptr) {
if (initialStr != nullptr) {
str = new char[strlen(initialStr) + 1];
strcpy(str, initialStr);
} else {
str = nullptr;
}
}

// Copy Constructor
cString(const cString& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}

// Destructor
~cString() {
delete[] str;
}

// Concatenate two strings


cString concatenate(const cString& other) const {
char* result = new char[strlen(str) + strlen(other.str) + 1];
strcpy(result, str);
strcat(result, other.str);
cString concatenatedString(result);
delete[] result;
return concatenatedString;
}

// Find the length of the string


int length() const {
return strlen(str);
}

// Reversing a string
cString reverse() const {
char* reversedStr = new char[strlen(str) + 1];
int length = strlen(str);
for (int i = 0; i < length; ++i) {
reversedStr[i] = str[length - 1 - i];
}
reversedStr[length] = '\0';
cString reversedString(reversedStr);
delete[] reversedStr;
return reversedString;
}

// Comparing two strings


int compare(const cString& other) const {
return strcmp(str, other.str);
}

// Display the string


void display() const {
std::cout << str << std::endl;
}
};

int main() {
cString str1("Hello");
cString str2("World");

// Copy Constructor
cString str3 = str1;

// Concatenate two strings


cString concatenated = str1.concatenate(str2);
std::cout << "Concatenated String: ";
concatenated.display();

// Find the length of the string


std::cout << "Length of str1: " << str1.length() << std::endl;

// Reversing a string
cString reversed = str1.reverse();
std::cout << "Reversed String: ";
reversed.display();

// Comparing two strings


int comparisonResult = str1.compare(str2);
std::cout << "Comparison Result: " << comparisonResult << std::endl;

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
9. Create a class to represent a 2-d shape and derive classes to represent a
triangle, rectangle and circle. Write a program using run-time polymorphism to
compute the area of the figures

AIM:

The aim of this program is to create a class called Shape2D to represent a 2D shape.
Derived classes Triangle, Rectangle, and Circle represent specific 2D shapes.
Each derived class implements the area() method to compute the area of its respective shape.
The program demonstrates run-time polymorphism by computing the area of different shapes.

ALGORITHM:

STEP1. Define a base class Shape2D to represent a 2D shape with a method area().
STEP 2. Define derived classes Triangle, Rectangle, and Circle representing specific 2D
shapes.
STEP 3. Implement area() method in each derived class to compute the area of the
corresponding shape.
STEP 4. Create instances of each class (Triangle, Rectangle, Circle) with appropriate
dimensions.
STEP 5. Use run-time polymorphism to call the area() method on each instance, which will
compute the area specific to each shape
PROGRAM:

#include<iostream>
#include<cmath>
class Shape {
public:
virtual float area() const = 0; // Pure virtual function for area calculation
};

class Triangle : public Shape {


private:
float base, height;
public:
Triangle(float b, float h) : base(b), height(h) {}

float area() const override {


return 0.5 * base * height;
}
};

class Rectangle : public Shape {


private:
float length, width;

public:
Rectangle(float l, float w) : length(l), width(w) {}

float area() const override {


return length * width;
}
};

class Circle : public Shape {


private:
float radius;

public:
Circle(float r) : radius(r) {}

float area() const override {


return 3.14 * radius * radius; // Approximating pi with 3.14
}
};

int main() {
// Example usage
Shape* shapes[] = {
new Triangle(4, 6),
new Rectangle(5, 8),
new Circle(3)
};

for (const auto& shape : shapes) {


std::cout << "Area: " << shape->area() << std::endl;
}

// Clean up allocated memory


for (const auto& shape : shapes) {
delete shape;
}
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
10. Define a class template representing a single-dimensional array. Implement
a function to sort the array elements. Include a mechanism to detect and throw
an exception for array-bound violations.

AIM:

The aim of this program is to define a class template called Array representing a single-
dimensional array.
The class provides the following functionalities:
Initialization of the array with a specified size.
Overloading [] operator to access and set array elements.
Implementing a function to sort the array elements.
Including mechanisms to detect and throw exceptions for array-bound violations.

ALGORITHM:

STEP 1. Define a class Array representing a single-dimensional array.


STEP 2. Implement _init_() method to initialize the array with a specified size.
STEP 3. Implement _getitem() and __setitem_() methods to overload the [] operator for
accessing and setting array elements.
STEP 4. Implement sort() method to sort the array elements using the sort() function.
STEP 5. Include mechanisms in _getitem() and __setitem_() methods to detect and throw
exceptions for array-bound violations.
PROGRAM:

#include<iostream>
#include<algorithm>
template <typename T, size_t Size>
class Array {
private:
T elements[Size];
public:
// Function to get the size of the array
size_t size() const {
return Size;
}

// Function to access elements with bounds checking


T& at(size_t index) {
if (index >= Size) {
throw std::out_of_range("Array index out of bounds");
}
return elements[index];
}

// Function to sort the array elements


void sort() {
std::sort(elements, elements + Size);
}
};

int main() {
try {
// Example usage with integers
Array<int, 5> intArray;

// Assigning values to array elements


for (size_t i = 0; i < intArray.size(); ++i) {
intArray.at(i) = rand() % 100; // Random values between 0 and 99
}

// Displaying unsorted array


std::cout << "Unsorted Array: ";
for (size_t i = 0; i < intArray.size(); ++i) {
std::cout << intArray.at(i) << " ";
}
std::cout << std::endl;

// Sorting array
intArray.sort();

// Displaying sorted array


std::cout << "Sorted Array: ";
for (size_t i = 0; i < intArray.size(); ++i) {
std::cout << intArray.at(i) << " ";
}
std::cout << std::endl;

// Accessing an out-of-bounds element (will throw an exception)


// Uncomment the next line to test the exception handling
// int outOfBoundsValue = intArray.at(10);
}
catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
11. Demonstrate the use of the vector STL container.

AIM:

The aim of this program is to demonstrate the use of the vector STL container in C++.
It includes creating a vector, adding elements to it, accessing and displaying elements, getting
the size of the vector, and clearing the vector.
This program showcases basic operations provided by the vector container in the C++ Standard
Library.

ALGORITHM:

STEP 1. Include the <vector> header file to use the vector container.
STEP 2. Declare a vector to store elements of a specific data type.
STEP 3. Use the push_back() method to add elements to the vector.
STEP 4. Use a loop to iterate over the elements of the vector and display them.
STEP 5. Access elements of the vector using indexing or the at() method.
STEP 6. Use the size() method to get the size of the vector.
STEP 7. Use the clear() method to remove all elements from the vector.
PROGRAM:

#include<iostream>
#include<vector>
int main() {
// Creating a vector of integers
std::vector<int> intVector;

// Adding elements to the vector


for (int i = 1; i <= 5; ++i) {
intVector.push_back(i * 10);
}

// Displaying the elements using an iterator


std::cout << "Vector Elements: ";
for (auto it = intVector.begin(); it != intVector.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;

// Using range-based for loop to display elements


std::cout << "Vector Elements (using range-based for loop): ";
for (const auto& element : intVector) {
std::cout << element << " ";
}
std::cout << std::endl;

// Accessing elements using index


std::cout << "Element at index 2: " << intVector[2] << std::endl;

// Modifying an element
intVector[3] = 99;

// Displaying modified vector


std::cout << "Modified Vector: ";
for (const auto& element : intVector) {
std::cout << element << " ";
}
std::cout << std::endl;

// Size and capacity of the vector


std::cout << "Vector Size: " << intVector.size() << std::endl;
std::cout << "Vector Capacity: " << intVector.capacity() << std::endl;

// Clearing the vector


intVector.clear();
std::cout << "Is Vector Empty? " << (intVector.empty() ? "Yes" : "No") << std::endl;

return 0;
}
OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.
12. Implement a telephone directory using files

AIM:

The aim of this program is to implement a telephone directory system using files in
C++.

ALGORITHM:

1. Define Data Structure: First, define a data structure to hold the information for each
entry in the telephone directory. This structure should include fields like name, phone
number, address, etc.
2. Menu Interface: Implement a menu-driven interface to allow users to perform
operations like adding a new entry, searching for an entry, updating an entry, deleting
an entry, and displaying all entries.
3. File Operations:
• Load Data: When the program starts, load the existing directory data from a
file into memory.
• Save Data: After any modification to the directory, save the updated data back
to the file.
4. Implement Operations:
• Add Entry: Prompt the user to input the details for a new entry and add it to
the directory data structure in memory. Also, save the updated data to the file.
• Search Entry: Allow users to search for entries by name, phone number, or any
other relevant field.
• Update Entry: Enable users to update the details of an existing entry.
• Delete Entry: Allow users to delete an entry from the directory.
• Display All Entries: Display all entries in the directory.
5. Error Handling: Implement error handling to deal with cases such as invalid input,
file read/write errors, etc.
6. Menu Loop: Create a loop that displays the menu, accepts user input, and executes the
corresponding operation until the user chooses to exit.
PROGRAM:

#include<iostream>
#include<fstream>
#include<string>
struct Contact {
std::string name;
std::string phoneNumber;
};
class TelephoneDirectory {
private:
std::fstream file;
public:
TelephoneDirectory(const std::string& fileName) {
file.open(fileName, std::ios::in | std::ios::out | std::ios::app);

if (!file.is_open()) {
std::cerr << "Error opening file: " << fileName << std::endl;
}
}
~TelephoneDirectory() {
file.close();
}
void addContact(const Contact& contact) {
file << contact.name << " " << contact.phoneNumber << std::endl;
}
void searchContact(const std::string& name) {
file.clear();
file.seekg(0);
std::string line;
while (std::getline(file, line)) {
size_t spacePos = line.find(' ');
std::string contactName = line.substr(0, spacePos);
if (contactName == name) {
std::cout << "Contact Found: " << line << std::endl;
return;
}
}
std::cout << "Contact not found." << std::endl;
}
void displayDirectory() {
file.clear(); // Clear any error flags
file.seekg(0); // Move to the beginning of the file
std::string line;
std::cout << "Telephone Directory:" << std::endl;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
}
};
int main() {
TelephoneDirectory directory("telephone_directory.txt");
Contact contact1 = { "John Doe", "123-456-7890" };
Contact contact2 = { "Jane Smith", "987-654-3210" };
directory.addContact(contact1);
directory.addContact(contact2);
directory.searchContact("Jane Smith");
directory.displayDirectory();
return 0;
}

OUTPUT:

RESULT:
Thus, the above program executed successfully and output verified.

You might also like