Sree Muthukumaraswamy College: Department of Bca Object Oriented Programming Using C++ Lab
Sree Muthukumaraswamy College: Department of Bca Object Oriented Programming Using C++ Lab
COLLEGE
92 / 1 & 9, Muthamizh Nagar, Kodungaiyur, Chennai – 118.
DEPARTMENT OF BCA
Name of Student :
Batch Number :
DEPARTMENT OF BCA
Name of Student :
Batch Number :
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.
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:
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) {}
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) {}
int main() {
// Creating two instances of the Point class
Point point1, point2;
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) {}
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
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 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) {}
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) {}
return hp;
}
return ap;
}
std::vector<double> ArithmeticProgression::generate(int numTerms) {
std::vector<double> ap;
double currentTerm = firstTerm;
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:
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";
}
}
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) {}
seconds %= 60;
minutes %= 60;
hours %= 24;
}
int main() {
// Creating an instance of the Time class
Time currentTime(10, 30, 45); // Example time: 10:30:45
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:
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:
#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:
#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:
// Copy Constructor
cString(const cString& other) {
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
// Destructor
~cString() {
delete[] 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;
}
int main() {
cString str1("Hello");
cString str2("World");
// Copy Constructor
cString str3 = str1;
// Reversing a string
cString reversed = str1.reverse();
std::cout << "Reversed String: ";
reversed.display();
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
};
public:
Rectangle(float l, float w) : length(l), width(w) {}
public:
Circle(float r) : radius(r) {}
int main() {
// Example usage
Shape* shapes[] = {
new Triangle(4, 6),
new Rectangle(5, 8),
new Circle(3)
};
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:
#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;
}
int main() {
try {
// Example usage with integers
Array<int, 5> intArray;
// Sorting array
intArray.sort();
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;
// Modifying an element
intVector[3] = 99;
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.