C++ Lab Manual
C++ Lab Manual
Lab Manual
Experiment 1
Class representing a complex number with member functions to perform the specified
operations.
1. Write a class to represent a complex number which has member functions to do the following
a. Set and show the value of the complex number
Aim
Algorithm
1. Start.
2. Define the ComplexNumber class with private variables real and imaginary.
3. Create a constructor to initialize real and imaginary with default or given values.
4. Add a function setValue to assign values to real and imaginary.
5. Add a function showValue to display the complex number in the format real + imaginary i.
6. In the main function, create an object complexNum of the ComplexNumber class.
7. Use setValue to assign the values 2 to real and 3 to imaginary.
8. Display the message "Complex Number:".
9. Use showValue to display the value of the complex number.
10. End.
Program
#include <iostream.h>
class ComplexNumber {
private:
double real;
double imaginary;
public:
// Constructor
ComplexNumber(double real = 0, double imaginary = 0) : real(real), imaginary(imaginary) {}
return 0;
}
Output:
Complex Number:
2 + 3i
Aim
Algorithm
1. Start.
2. Define the ComplexNumber class with private variables real and imaginary.
3. Create a constructor to initialize real and imaginary with default or given values.
4. Add a function add to return the sum of two complex numbers.
5. Add a function subtract to return the difference of two complex numbers.
6. Add a function multiply to return the product of two complex numbers.
7. Add a display function to print a complex number in the format real + imaginary i.
8. In the main function, create two objects complexNum1 and complexNum2 with initial values.
9. Perform addition, subtraction, and multiplication using the member functions, storing the results in
new objects.
10. Display the original numbers and the results of the operations using the display function. End.
Program
#include <iostream.h>
class ComplexNumber {
private:
double real;
double imaginary;
public:
// Constructor
ComplexNumber(double real = 0, double imaginary = 0) : real(real), imaginary(imaginary) {}
// Member functions for addition, subtraction, and multiplication
ComplexNumberadd(constComplexNumber& other) const {
return ComplexNumber(real + other.real, imaginary + other.imaginary);
}
int main() {
// Creating two instances of ComplexNumber
ComplexNumber complexNum1(2, 3);
ComplexNumber complexNum2(1, -2);
// Performing operations
ComplexNumberresultAdd = complexNum1.add(complexNum2);
ComplexNumberresultSubtract = complexNum1.subtract(complexNum2);
ComplexNumberresultMultiply = complexNum1.multiply(complexNum2);
// Displaying results
std::cout<< "Complex Number 1:" << std::endl;
complexNum1.display();
return 0;
}
Output
Complex Number 1:
2 + 3i
Complex Number 2:
1 + -2i
Addition:
3 + 1i
Subtraction:
1 + 5i
Multiplication:
8 + -1i
Aim
To write a C++ program to multiply the complex number with a scalar value
Algorithm
1. Start.
2. Define the ComplexNumber class with private variables real and imaginary.
3. Create a constructor to initialize real and imaginary with default or given values.
4. Add a function multiplyByScalar to return a new complex number by multiplying real and imaginary
with a given scalar.
5. Add a display function to print the complex number in the format real + imaginary i.
6. In the main function, create a ComplexNumber object complexNum with initial values 2 and 3.
7. Call multiplyByScalar with a scalar value (e.g., 2), store the result in a new object, and display both the
original and resulting complex numbers.
8. End.
Program:
#include <iostream>
class ComplexNumber {
private:
double real;
double imaginary;
public:
// Constructor
ComplexNumber(double real = 0, double imaginary = 0) : real(real), imaginary(imaginary) {}
// Multiplying by a scalar
double scalarValue = 2;
ComplexNumber result = complexNum.multiplyByScalar(scalarValue);
// Displaying results
std::cout<< "Original Complex Number:" << std::endl;
complexNum.display();
return 0;
}
Output
Original Complex Number:
2 + 3i
Multiplication by Scalar:
4 + 6i
Experiment 2
Algorithm:
1. Start.
2. Define the Point class with private variables x and y to represent the coordinates.
3. Create a constructor to initialize x and y with default or given values.
4. Add a setPoint function to update the coordinates of the point.
5. Add a showPoint function to display the coordinates of the point in the format (x, y).
6. In the main function, create a Point object named myPoint.
7. Use showPoint to display the initial coordinates and setPoint to update the coordinates to (3.0, 4.0).
8. Call showPoint again to display the updated coordinates. End.
Program:
#include <iostream>
class Point
{
private:
double x;
double y;
public:
// Constructor to initialize the point
Point(double initialX = 0.0, double initialY = 0.0) : x(initialX), y(initialY)
{
}
int main() {
// Example usage:
return 0;
Output:
Point coordinates: (0, 0)
Point coordinates: (3, 4)
2. b.Write a Point class that represents a 2-d point in a plane. Write member functions
to,Find the distance between two points
Aim: To write a C++ program to find the distance between tow points
Algorithm
1. Start.
2. Define the Point class with private variables x and y to represent coordinates.
3. Create a constructor to initialize x and y with default or given values.
4. Add a setPoint function to update the coordinates of the point.
5. Add a showPoint function to display the coordinates of the point in the format (x, y).
6. Add a distanceTo function to calculate the Euclidean distance between the current point and
another point.
7. In the main function, create two Point objects (point1 and point2) with initial coordinates.
8. Display the coordinates of both points using showPoint, calculate the distance using
distanceTo, and display the result. End.
Program
#include <iostream>
#include <cmath>
class Point
{
private:
double x;
double y;
public:
// Constructor to initialize the point
Point(double initialX = 0.0, double initialY = 0.0) : x(initialX), y(initialY)
{
}
// Member function to set the coordinates of the point
void setPoint(double newX, double newY)
{
x = newX;
y = newY;
}
int main()
{
// Example usage:
// Create two Point objects
Point point1(1.0, 2.0);
Point point2(4.0, 6.0);
return 0;
}
Output:
Point coordinates: (1, 2)
Point coordinates: (4, 6)
Distance between the points: 5
2.c.Write a Point class that represents a 2-d point in a plane. Write member functions
to, check whether two points are equal or not
Aim : To write a C++ program to check if two point are equal or not
Algorithm:
1. Start.
2. Define the Point class with private variables x and y to represent coordinates.
3. Create a constructor to initialize x and y with default or given values.
4. Add a setPoint function to update the coordinates of the point.
5. Add a showPoint function to display the coordinates of the point in the format (x, y).
6. Add an isEqual function to compare two points and check if their coordinates are equal.
7. In the main function, create three Point objects (point1, point2, and point3) with specific
coordinates.
8. Display the coordinates of the points using showPoint and use isEqual to compare the points,
displaying the results. End.
Program
#include <iostream>
class Point {
private:
double x;
double y;
public:
// Constructor to initialize the point
Point(double initialX = 0.0, double initialY = 0.0) : x(initialX), y(initialY) {}
int main() {
// Example usage:
return 0;
}
Output:
Point coordinates: (3, 4)
Point coordinates: (3, 4)
Point coordinates: (1, 2)
point1 and point2 are equal.
point1 and point3 are not equal.
Experiment 3
Design and implement a class to represent a Harmonic Progression (HP) and Arithmetic
Progression.
a. Generate the HP up to a specified number of terms
Algorithm:
1. Start.
2. Input the first term aa, common difference dd, and the number of terms nn.
3. Define the function generateHarmonicProgression that takes aa, dd, and nn as arguments.
4. Inside the function, initialize an empty vector progression.
5. Use a loop to compute each term of the harmonic progression as 1a+i⋅d\frac{1}{a + i \cdot d} for
i=0i = 0 to n−1n-1.
6. Append each computed term to the vector progression. Return the vector after the loop ends.
7. Call the generateHarmonicProgression function with the input values aa, dd, and nn.
8. Store the returned vector in a variable result.
9. Display the harmonic progression by iterating through result and printing each term.
10. End.
Program
#include <iostream>
#include <vector>
std::vector<double>generateHarmonicProgression(double a, double d, int n) {
std::vector<double> progression;
for (int i = 0; i< n; ++i) {
progression.push_back(1 / (a + i * d));
}
return progression;
}
int main() {
double a, d;
int n;
// Input the first term (a), common difference (d), and number of terms (n)
std::cout<< "Enter the first term (a): ";
std::cin>> a;
Aim: To write a C++ program to calculate the sum of HP to n terms and to infinity
Algorithm
1. Start.
2. Input the number of terms nn.
3. Define the function sumHarmonicProgressionFinite that takes nn as input and calculates the sum
of the harmonic progression up to nn terms.
4. Inside the function, initialize a variable sum to 0.0, and use a loop to add the reciprocal of each
integer from 1 to nn to sum.
5. Return the computed sum.
6. Define the function sumHarmonicProgressionInfinity to calculate the sum of the harmonic
progression approaching infinity.
7. Inside the function, initialize a variable sum to 0.0 and a variable i to 1. Use a while loop to keep
adding terms until the sum no longer changes significantly when adding the next term.
8. In main, call both functions and display the results: the sum for nn terms and the sum
approaching infinity. End.
Program
#include <iostream>
double sumHarmonicProgressionFinite(int n) {
double sum = 0.0;
for (int i = 1; i<= n; ++i) {
sum += 1.0 / i;
}
return sum;
}
double sumHarmonicProgressionInfinity() {
double sum = 0.0;
int i = 1;
while (true) {
sum += 1.0 / i;
if (sum == sum + 1.0 / (i + 1)) {
// Break if adding the next term does not change the sum significantly
break;
}
i++;
}
return sum;
}
int main() {
int n;
// Calculate and display the sum of the harmonic progression approaching infinity
double sumInfinity = sumHarmonicProgressionInfinity();
std::cout<< "Sum of Harmonic Progression approaching Infinity: " <<sumInfinity<<
std::endl;
return 0;
}
Output
Enter the number of terms (n): 6
Sum of Harmonic Progression up to 6 terms: 2.45
Sum of Harmonic Progression approaching Infinity: inf
Algorithm
1. Start.
2. Define the HarmonicProgression class with a static function nthTerm to calculate the nth term.
3. Inside nthTerm, check if nn is greater than 0. If not, display an error message and return 0.0.
4. If nn is valid, calculate the nth term as 1n\frac{1}{n} and return the result.
5. In the main function, prompt the user to input the value of nn.
6. Call HarmonicProgression::nthTerm(n) to get the nth term.
7. Display the result of the nth term.
8. End.
Program
#include <iostream>
class HarmonicProgression {
public:
static double nthTerm(int n) {
// Ensure that n is greater than 0
if (n <= 0) {
std::cerr<< "Error: n should be greater than 0." <<std::endl;
return 0.0;
}
// Calculate the nth term of the Harmonic Progression
return 1.0 / n;
}
};
int main() {
// Get the nth term of the Harmonic Progression
int n;
std::cout<< "Enter the value of n for the nth term: ";
std::cin>> n;
return 0;
}
Output
Enter the value of n for the nth term: 6
The nth term of the Harmonic Progression is: 0.166667
Algorithm
1. Start.
2. Define the ArithmeticProgression class with private variables firstTerm and commonDifference.
3. Create a constructor in ArithmeticProgression to initialize firstTerm and commonDifference.
4. Define a member function nthTerm in ArithmeticProgression to calculate the nth term using the
formula: firstTerm+(n−1)×commonDifference\text{firstTerm} + (n - 1) \times
\text{commonDifference}.
5. Define the HarmonicProgression class with a static function calculateSum that calculates the sum
of the reciprocals of the first nn terms of an ArithmeticProgression.
6. Inside calculateSum, loop through the first nn terms, calculate the reciprocal of each term from
ArithmeticProgression, and add it to the sum.
7. In the main function, create an ArithmeticProgression object ap with a first term of 2 and a
common difference of 3.
8. Call HarmonicProgression::calculateSum(ap, n) with n=5n = 5, display the result, and end.
Program
#include <iostream>
class ArithmeticProgression {
private:
int firstTerm;
int commonDifference;
public:
ArithmeticProgression(int first, int diff) : firstTerm(first), commonDifference(diff) {}
class HarmonicProgression {
public:
static double calculateSum(const ArithmeticProgression& ap, int n) {
double sum = 0.0;
for (int i = 1; i<= n; ++i) {
sum += 1.0 / ap.nthTerm(i);
}
return sum;
}
};
int main() {
// Create an Arithmetic Progression with first term 2 and common difference 3
ArithmeticProgressionap(2, 3);
// Use the Harmonic Progression class to calculate the sum of the reciprocals of the first 5
terms
int n = 5;
double sum = HarmonicProgression::calculateSum(ap, n);
return 0;
}
Output
Sum of the reciprocals of the first 5 terms: 0.987338
Experiment 4
Design and implement a class to represent a Solid object to calculate Volume and surface
area.
Aim: To write a C++ program to represent a data member to calculate volume and surface
area
Algorithm
1. Start.
2. Define the Shapes class with private variables: type, d1, d2, d3, tsa (total surface area), and vol
(volume).
3. Define the get function to prompt the user for a shape option (1 for cube, 2 for cuboid, 3 for sphere, 4
to exit).
4. Based on the input, call the respective function: If type is 1, call f1 (cube); if type is 2, call f2 (cuboid);
if type is 3, call f3 (sphere); if type is 4, exit the program; if the input is invalid, print an error message.
5. Define the f1 function for the cube: Prompt the user for the side of the cube (d1), calculate the total
surface area (tsa = 6 * d1 * d1) and volume (vol = d1 * d1 * d1), and display the results.
6. Define the f2 function for the cuboid: Prompt the user for the length, width, and height (d1, d2, d3),
calculate the total surface area (tsa = 2 * (d1 * d2 + d2 * d3 + d1 * d3)) and volume (vol = d1 * d2 *
d3), and display the results.
7. Define the f3 function for the sphere: Prompt the user for the radius (d1), calculate the total surface
area (tsa = 4 * 3.14 * d1 * d1) and volume (vol = (4.0 / 3.0) * 3.14 * d1 * d1 * d1), and display the
results.
8. In the main function, create an object s of the Shapes class and call the get function.
9. End.
Program
#include <iostream>
using namespace std;
class Shapes {
private:
int type;
float d1, d2, d3;
float tsa, vol;
public:
void get() {
cout << "1. CUBE\n2. CUBOID\n3. SPHERE\n4. EXIT\nEnter your option: ";
cin >> type;
if (type == 1)
f1();
else if (type == 2)
f2();
else if (type == 3)
f3();
else if (type == 4)
exit(0);
else
cout << "Invalid option. Please enter 1, 2, 3, or 4 and try again.\n";
}
void f1() {
cout << "Enter the side of the cube: ";
cin >> d1;
tsa = 6 * d1 * d1;
vol = d1 * d1 * d1;
cout << "Total surface area of the cube: " << tsa << endl;
cout << "Volume of the cube: " << vol << endl;
}
void f2() {
cout << "Enter the length, width, and height of the cuboid: ";
cin >> d1 >> d2 >> d3;
tsa = 2 * (d1 * d2 + d2 * d3 + d1 * d3);
vol = d1 * d2 * d3;
cout << "Total surface area of the cuboid: " << tsa << endl;
cout << "Volume of the cuboid: " << vol << endl;
}
void f3() {
cout << "Enter the radius of the sphere: ";
int main() {
Shapes s;
s.get();
return 0;
}
Output
1. CUBE
2. CUBOID
3. SPHERE
4. EXIT
Enter your option: 2
Enter the length, width, and height of the cuboid: 3
4
6
Total surface area of the cuboid: 108
Volume of the cuboid: 72
Experiment 5
Aim
To write a c++ program to write a class representing time find difference adding given time conversion
to seconds
Algorithm
1. Start by defining the Time class with private variables seconds, hh (hours), mi (minutes), and ss
(seconds).
2. Define the setTime function to set the time by accepting hours, minutes, and seconds as
parameters and assigning them to hh, mi, and ss.
3. Define the displayTime function to display the time in the format hh:mm:ss using proper
formatting with setw and setfill.
4. Define the convertToSeconds function to convert the time into total seconds using the formula
seconds = hh * 3600 + mi * 60 + ss, and then display the total seconds.
5. Define the calculateTimeDifference function to calculate the difference between two Time
objects (t1 and t2) by subtracting their respective hours, minutes, and seconds. Handle cases
where seconds or minutes go below zero by adjusting the values accordingly.
6. Define the addDuration function to add a given duration (in seconds) to the time. Update the
hours, minutes, and seconds accordingly, ensuring that the seconds and minutes do not exceed
their respective limits.
7. In the main function, create two Time objects (t1 and t2), set their times, display them, and
convert t1 to seconds. Then, calculate and display the time difference between t1 and t2.
8. Prompt the user to input a duration in seconds to add to t2, then display the updated time of t2.
End the program.
Program
#include <iostream>
#include <iomanip>
class Time {
private:
long seconds;
int hh, mi, ss;
public:
void setTime(int h, int m, int s) {
hh = h;
mi = m;
ss = s;
}
void displayTime() const {
std::cout << "The time is = " << std::setw(2) << std::setfill('0') << hh << ":"
<< std::setw(2) << std::setfill('0') << mi << ":"
<< std::setw(2) << std::setfill('0') << ss << std::endl;
}
void convertToSeconds() {
seconds = hh * 3600 + mi * 60 + ss;
std::cout << "Seconds = " << seconds << std::endl;
}
if (temp.ss < 0) {
temp.ss += 60;
temp.mi--;
}
if (temp.mi < 0) {
temp.mi += 60;
temp.hh--;
}
return temp;
}
int main() {
Time t1, t2, result;
t1.setTime(15, 15, 35);
t1.displayTime();
t1.convertToSeconds();
result = t1.calculateTimeDifference(t2);
std::cout << "Difference between the two time objects :";
result.displayTime();
int seconds;
std::cout << "Enter duration to be added in seconds: ";
std::cin >> seconds;
t2.addDuration(seconds);
t2.displayTime();
return 0;
}
Output
The time is = 15:15:35
Seconds = 54935
The time is = 10:10:20
Difference between the two time objects :The time is = 05:05:15
Enter duration to be added in seconds: 3701
The time is = 11:12:01
Experiment 6
Design a 3x3 matrix class and demonstrate add,multiply and count the objects.
Algorithm
1. Define the Matrix3x3 class with a private member data, a 3x3 matrix stored as a 2D vector.
2. Create a constructor that accepts a 3x3 matrix as input, checks its validity, and throws an
exception if it is not a 3x3 matrix.
3. Define the operator+ function to add two 3x3 matrices. Iterate through each element, adding the
corresponding elements of both matrices and storing the result in a new matrix.
4. Define the operator* function to multiply two 3x3 matrices. Implement matrix multiplication by
iterating through rows and columns and summing the products of corresponding elements.
5. Implement the operator<< function to output a 3x3 matrix. Iterate through each row and print the
elements in a formatted manner.
6. In the main function, initialize two Matrix3x3 objects (matrix1 and matrix2) with predefined 3x3
matrices.
7. Display matrix1 and matrix2 using the overloaded << operator.
8. Perform matrix addition and multiplication on matrix1 and matrix2 and display the results.
Program
#include <iostream>
#include <vector>
class Matrix3x3 {
private:
std::vector<std::vector<int>> data;
public:
Matrix3x3(const std::vector<std::vector<int>>&input_data) : data(input_data) {
if (data.size() != 3 || data[0].size() != 3 || data[1].size() != 3 || data[2].size() != 3) {
throw std::invalid_argument("Matrix must be 3x3");
}
}
os<<std::endl;
}
return os;
}
};
int main() {
Matrix3x3 matrix1({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
Matrix3x3 matrix2({{9, 8, 7}, {6, 5, 4}, {3, 2, 1}});
return 0;
}
Output:
Matrix 1:
123
456
789
Matrix 2:
987
654
321
Matrix 1 + Matrix 2:
10 10 10
10 10 10
10 10 10
Matrix 1 * Matrix 2:
30 24 18
84 69 54
138 114 90
6.b. Maintaining a count of the number of matrix object created
Aim To write a C++ program to create a matrix object creating
Algorithm
1. Define Matrix3x3 class with a 2D vector data and static count variable.
2. Implement constructor to initialize matrix and check if it's 3x3. Increment count on object
creation.
3. Define operator+ to add two 3x3 matrices element-wise.
4. Define operator* to multiply two 3x3 matrices.
5. Create getCount() function to return the count of Matrix3x3 objects.
6. Implement operator<< to print matrix in a 3x3 format.
7. In main, create two Matrix3x3 objects (matrix1 and matrix2) with 3x3 data.
8. Display matrices and print object count using getCount().
Program
#include <iostream>
#include <vector>
class Matrix3x3 {
private:
std::vector<std::vector<int>> data;
static int count; // Static member variable to count objects
public:
Matrix3x3(const std::vector<std::vector<int>>&input_data) : data(input_data) {
if (data.size() != 3 || data[0].size() != 3 || data[1].size() != 3 || data[2].size() != 3) {
throw std::invalid_argument("Matrix must be 3x3");
}
count++; // Increment count when an object is created
}
}
};
int main() {
Matrix3x3 matrix1({{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
Matrix3x3 matrix2({{9, 8, 7}, {6, 5, 4}, {3, 2, 1}});
std::cout<< "Number of Matrix objects created: " << Matrix3x3::getCount() << std::endl;
return 0;
}
Output
Matrix 1:
123
456
789
Matrix 2:
987
654
321
Create a data member in the class to represent a string using an array of size 100 to
perform string operations.
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
Aim To write a C++ program to create a data member string using array size 100
Algorithm
1. Define a class cString with a private character array data[100] to store the string.
2. Create a parameterized constructor that takes a const char* input, copies it to data using strncpy,
and ensures null-termination.
3. Implement a copy constructor that copies the data from another cString object into the current
object and ensures null-termination.
4. Add a getter function getData() that returns the string stored in data.
5. In the main() function, create an object str1 of class cString initialized with the string "Hello".
6. Create another object str2 as a copy of str1 to invoke the copy constructor.
7. Print the original string using std::cout and str1.getData().
8. Print the copied string using std::cout and str2.getData().
Program
#include <iostream>
#include <cstring>
class cString {
private:
char data[100];
public:
cString(const char* str) {
if (str != nullptr) {
strncpy(data, str, 99);
data[99] = '\0'; // Ensure null-termination
} else {
data[0] = '\0';
}
}
int main() {
cString str1("Hello");
cString str2(str1); // Copy constructor called
return 0;
}
Output:
Original string: Hello
Copied string: Hello
b. Concatenate two strings
Aim To write a C++ program to concatenate two strings
Algorithm
1. Define a class cString with a private character array data[100] to store the string.
2. Implement a parameterized constructor that copies the input string to data using strncpy and
ensures null-termination.
3. Define a member function concatenate() that takes another cString object as input and appends its
data to the current object's data using strncat.
4. Ensure the concatenation avoids buffer overflow by limiting the number of characters appended.
5. Add a getter function getData() to return the string stored in data.
6. In the main() function, create two cString objects, str1 initialized with "Hello" and str2 initialized
with " world".
7. Print the original strings of str1 and str2 using getData().
8. Call concatenate() to append str2 to str1, then print the concatenated string using getData().
Program
#include <iostream>
#include <cstring>
class cString {
private:
char data[100];
public:
cString(const char* str) {
if (str != nullptr) {
strncpy(data, str, 99);
data[99] = '\0'; // Ensure null-termination
} else {
data[0] = '\0';
}
}
void concatenate(const cString& other) {
strncat(data, other.data, 100 - strlen(data) - 1);
}
int main() {
cString str1("Hello");
cString str2(" world");
return 0;
}
Output
Original string 1: Hello
Original string 2: world
Concatenated string: Hello world
Algorithm
1. Define a class cString with a private static constant MAX_LENGTH set to 100 and a character
array str of size MAX_LENGTH + 1 to store the string.
2. Implement a default constructor to initialize str as an empty string by setting the first character to
'\0'.
3. Add a parameterized constructor that takes a const char* input, copies it to str using strncpy, and
ensures null-termination by setting str[MAX_LENGTH] to '\0'.
4. Implement a member function length() to calculate and return the length of the string using strlen.
5. In the main() function, create an object myString of class cString, initializing it with the string
"Hello, World!".
6. Call the length() member function on myString to determine the length of the string stored in the
object.
7. Print the calculated length using std::cout.
8. End the program successfully with a return 0 statement.
Program
#include <iostream>
#include <cstring>
class cString {
private:
static const int MAX_LENGTH = 100;
char str[MAX_LENGTH + 1]; // +1 for null terminator
public:
cString() {
str[0] = '\0'; // Initialize empty string
}
cString(const char* s) {
strncpy(str, s, MAX_LENGTH);
str[MAX_LENGTH] = '\0'; // Ensure null termination
}
int main() {
cString myString("Hello, World!");
std::cout << "Length of the string: " << myString.length() << std::endl;
return 0;
}
Output:
Length of the string: 13
d Reversing a string
Aim
Algorithm
1. Define a class cString with a private character array data[100] to store the string.
2. Implement a parameterized constructor to copy an input string into data using strncpy, ensuring
null-termination.
3. Define a member function reverse() that calculates the length of the string in data using strlen.
4. In the reverse() function, swap the characters symmetrically from the start and end of the string
until the middle is reached.
5. Add a getter function getData() to return the stored string from data.
6. In the main() function, create two cString objects, str1 initialized with "Hello" and str2 initialized
with "World".
7. Print the original strings of str1 and str2 using getData().
8. Call reverse() on both objects to reverse their strings and print the reversed strings using
getData().
Program
#include <iostream>
#include <cstring>
public:
cString(const char* str) {
if (str != nullptr) {
strncpy(data, str, 99);
data[99] = '\0'; // Ensure null-termination
} else {
data[0] = '\0';
}
}
void reverse() {
int length = strlen(data);
for (int i = 0; i< length / 2; ++i) {
char temp = data[i];
data[i] = data[length - i - 1];
data[length - i - 1] = temp;
}
int main() {
cString str1("Hello");
cString str2("World");
str1.reverse();
str2.reverse();
return 0;
}
Output
Original string 1: Hello
Original string 2: World
Reversed string 1: olleH
Reversed string 2: dlroW
Algorithm
1. Define a class cString with a private character array data[100] to store a string.
2. Implement a parameterized constructor to copy an input string into data using strncpy, ensuring
null-termination.
3. Define a member function compare() that takes another cString object as input and compares the
data of both objects using strcmp.
4. Return the comparison result, which is 0 if the strings are equal, negative if the current string is
lexicographically smaller, or positive if it is larger.
5. Add a getter function getData() to return the stored string from data.
6. In the main() function, create two cString objects, str1 initialized with "Hello" and str2 initialized
with "World".
7. Print the original strings of str1 and str2 using getData().
8. Call the compare() function to compare the two strings and print the result, indicating whether the
strings are equal, or which one comes first lexicographically.
Program
#include <iostream>
#include <cstring>
class cString {
private:
char data[100];
public:
cString(const char* str) {
if (str != nullptr) {
strncpy(data, str, 99);
data[99] = '\0'; // Ensure null-termination
} else {
data[0] = '\0';
}
}
int main() {
cString str1("Hello");
cString str2("World");
if (result == 0) {
std::cout<< "String 1 and String 2 are equal." <<std::endl;
} else if (result < 0) {
std::cout<< "String 1 comes before String 2." <<std::endl;
} else {
std::cout<< "String 1 comes after String 2." <<std::endl;
}
return 0;
}
Output:
String 1: Hello
String 2: World
String 1 comes before String 2.
Experiment 8
Create a data member in the class to represent a string whose size is dynamically
allocated and perform string operations.
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
Aim To write a C++ program to create dynamic allocated string with copy constructor
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor to initialize data to nullptr.
3. Create a parameterized constructor that allocates memory dynamically for the input string,
copies it using strcpy, and ensures proper null-termination.
4. Define a copy constructor that creates a deep copy of another cString object's data by allocating
new memory and copying the string content.
5. Implement a destructor to release the dynamically allocated memory using delete[] to prevent
memory leaks.
6. Add a getter function getData() to return the stored string.
7. In the main() function, create an object str1 of class cString, initialized with "Hello".
8. Create another object str2 as a copy of str1 (invokes the copy constructor), and print both strings
using getData().
Program
#include <iostream>
#include <cstring>
class cString {
private:
char* data;
public:
// Default constructor
cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
data = new char[strlen(str) + 1];
strcpy(data, str);
} else {
data = nullptr;
}
}
// Copy constructor
cString(const cString& other) {
if (other.data != nullptr) {
data = new char[strlen(other.data) + 1];
strcpy(data, other.data);
} else {
data = nullptr;
}
}
// Destructor
~cString() {
delete[] data;
}
int main() {
cString str1("Hello");
cString str2(str1); // Copy constructor called
return 0;
}
Output
Original string: Hello Copied string: Hello
b.Destructor
Aim To write a C++ program with destructor
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor that initializes data to nullptr.
3. Create a parameterized constructor that checks if the input string is not nullptr. If valid,
dynamically allocate memory for the string, copy it using strcpy, and ensure proper null-
termination. If the input is nullptr, set data to nullptr.
4. Define a destructor that deallocates the dynamically allocated memory for data using delete[] to
avoid memory leaks.
5. Add a getter function getData() to return the string stored in data.
6. In the main() function, create an object str1 of class cString, initialized with the string "Hello".
7. Use the getData() function to print the string stored in str1 using std::cout.
8. Allow the program to terminate, automatically invoking the destructor to release the dynamically
allocated memory when str1 goes out of scope.
Program
#include <iostream>
#include <cstring>
public:
// Default constructor cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
// Destructor
~cString() {
delete[] data;
}
int main() {
cString str1("Hello");
Output:
Original string: Hello
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor that initializes data to nullptr.
3. Create a parameterized constructor that dynamically allocates memory for the input string, copies
the string using strcpy, and ensures null-termination.
4. Define a destructor that releases the dynamically allocated memory for data using delete[] to
prevent memory leaks.
5. Implement a concatenate() method that checks if the input string is nullptr, calculates the length of
the existing string and the new string, allocates new memory for the concatenated result, copies the
existing string using strcpy, and appends the new string using strcat. Then, delete the old memory
and assign the new memory to data.
6. Add a getter function getData() to return the stored string.
7. In the main() function, create two cString objects, str1 initialized with "Hello" and str2 initialized
with " World".
8. Call the concatenate() method on str1 to append the string from str2, and print the original and
concatenated strings using getData().
Program
#include <iostream>
#include <cstring>
public:
// Default constructor cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
data = new char[strlen(str) + 1];
strcpy(data, str);
} else {
data = nullptr;
}
}
// Destructor
~cString() {
delete[] data;
}
// Concatenate method
void concatenate(const char* str) {
if (str == nullptr) return;
strcpy(newData, data);
strcat(newData, str);
delete[] data;
data = newData;
}
// Getter function for data
const char* getData() const {
return data;
}
};
int main() {
cString str1("Hello");
cString str2(" World");
str1.concatenate(str2.getData());
return 0;
}
Output
Original string 1: Hello
Original string 2: World
Concatenated string: Hello World
d. Find the length of the string
Aim To write a C++ program to find length of the string
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor that initializes data to nullptr.
3. Create a parameterized constructor that checks if the input string is not nullptr, then dynamically
allocates memory for the string, copies it using strcpy, and ensures null-termination.
4. Define a destructor that deallocates the dynamically allocated memory for data using delete[].
5. Implement a length() method that returns 0 if data is nullptr, otherwise calculates and returns the
length of the string using strlen.
6. Add a getter function getData() that returns the stored string in data.
7. In the main() function, create a cString object str1 initialized with the string "Hello".
8. Print the string using getData() and its length using length() method.
Program
#include <iostream>
#include <cstring>
class cString {
private:
char* data;
public:
// Default constructor
cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
data = new char[strlen(str) + 1];
strcpy(data, str);
} else {
data = nullptr;
}
}
// Destructor
~cString() {
delete[] data;
}
// Length method
int length() const {
if (data == nullptr) {
return 0;
} else {
return strlen(data);
}
}
int main() {
cString str1("Hello");
return 0;
}
Output
String 1: Hello
Length of String 1: 5
e. Reversing a string
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor that initializes data to nullptr.
3. Create a parameterized constructor that checks if the input string is not nullptr. If valid,
dynamically allocate memory for the string, copy it using strcpy, and ensure null-termination.
4. Define a destructor that deallocates the dynamically allocated memory for data using delete[].
5. Implement a reverse() method that checks if data is not nullptr, calculates the length of the string
using strlen, and then swaps characters symmetrically from the start and end of the string until the
middle is reached.
6. Add a getter function getData() to return the string stored in data.
7. In the main() function, create a cString object str1 initialized with the string "Hello".
8. Print the original string using getData(), call the reverse() method to reverse the string, and then
print the reversed string.
Program
#include <iostream>
#include <cstring>
class cString {
private:
char* data;
public:
// Default constructor
cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
data = new char[strlen(str) + 1];
strcpy(data, str);
} else {
data = nullptr;
}
}
// Destructor
~cString() {
delete[] data;
}
// Reverse method
void reverse() {
if (data == nullptr) return;
int main() {
cString str1("Hello");
return 0;
}
Output:
Original string: Hello
Reversed string: olleH
Algorithm
1. Define a class cString with a private pointer data to store the string dynamically.
2. Implement a default constructor that initializes data to nullptr.
3. Create a parameterized constructor that dynamically allocates memory for the input string if it's
not nullptr and copies it using strcpy.
4. Define a destructor to release the dynamically allocated memory for data using delete[].
5. Implement a compare() method that compares the current string with another cString object using
strcmp.
6. In the compare() method, handle cases where one or both strings are nullptr and return the
appropriate comparison result.
7. Add a getter function getData() to return the stored string in data.
8. In the main() function, create two cString objects, str1 and str2, compare them using the
compare() method, and print the result based on the comparison.
Program
#include <iostream>
#include <cstring>
class cString {
private:
char* data;
public:
// Default constructor
cString() : data(nullptr) {}
// Parameterized constructor
cString(const char* str) {
if (str != nullptr) {
data = new char[strlen(str) + 1];
strcpy(data, str);
} else {
data = nullptr;
}
}
// Destructor
~cString() {
delete[] data;
}
// Compare method
int compare(const cString& other) const {
if (data == nullptr&&other.data == nullptr) return 0;
if (data == nullptr) return -1;
if (other.data == nullptr) return 1;
return strcmp(data, other.data);
}
// Getter function for data
const char* getData() const {
return data;
}};
int main() {
cString str1("Hello");
cString str2("World");
std::cout<< "String 1: " << str1.getData() << std::endl;
std::cout<< "String 2: " << str2.getData() << std::endl;
int result = str1.compare(str2);
if (result == 0) {
std::cout<< "String 1 and String 2 are equal." <<std::endl;
} else if (result < 0) {
std::cout<< "String 1 comes before String 2." <<std::endl;
} else {
std::cout<< "String 1 comes after String 2." <<std::endl;
return 0;
}
Output:
String 1: Hello
String 2: World
String 1 comes before String 2.
Experiment 9
Run time polymorphism
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
Algorithm
1. Define a Shape class as an abstract base class with a pure virtual function area() to calculate the
area of a shape. Include a virtual destructor.
2. Define a Triangle class that inherits from Shape, with member variables base and height.
Implement the area() function to calculate the area of a triangle.
3. Define a Rectangle class that inherits from Shape, with member variables length and width.
Implement the area() function to calculate the area of a rectangle.
4. Define a Circle class that inherits from Shape, with a member variable radius. Implement the
area() function to calculate the area of a circle.
5. In the main() function, create an array of Shape* to store pointers to different shapes (triangle,
rectangle, circle), calculate and print their areas in a loop, and then delete the dynamically
allocated shapes to free memory.
Program
#include <iostream>
class Shape {
public:
virtual double area() const = 0;
virtual ~Shape() {}
};
int main() {
Shape* shapes[3];
shapes[0] = new Triangle(5, 3);
shapes[1] = new Rectangle(4, 6);
shapes[2] = new Circle(2);
return 0;
}
Output
Area of shape 1: 7.5
Area of shape 2: 24
Area of shape 3: 12.5664
Experiment 10
Algorithm
1. Define a template class Array that accepts a type T and a size Size to create a fixed-size array.
2. In the class, declare a private member elements to store the array of type T with the specified
size.
3. Implement a getter and setter function operator[] to allow accessing and modifying elements of
the array. If an invalid index is accessed (greater than or equal to Size), throw an
std::out_of_range exception.
4. Overload the operator[] to provide a const version that returns a reference to the array element
for constant access, also checking for valid indices.
5. Implement a sort() function that uses the bubble sort algorithm to sort the elements of the array
in ascending order.
6. In the main() function, create an instance of the Array class with integer type and size 5.
7. Initialize the array with values, print the values before sorting, call the sort() method, and print
the sorted values.
8. Attempt to access an out-of-bounds index to trigger and catch the std::out_of_range
exception, printing the error message if the exception is thrown.
Program
#include <iostream>
#include <stdexcept>
public:
Array() {}
int main() {
try {
Array<int, 5> arr;
arr[0] = 5;
arr[1] = 2;
arr[2] = 8;
arr[3] = 1;
arr[4] = 3;
arr.sort();
return 0;
}
Output
Before sorting:
52813
After sorting:
12358
Exception: Index out of range
Experiment 11
Demonstrate the use of the vector STL container.
Algorithm
Program
#include <iostream>
#include <vector>
int main() {
// Creating a vector of integers
std::vector<int> numbers;
// Modifying elements
numbers[1] = 25;
return 0;
}
Output
Elements in the vector: 10 20 30
Elements in the vector using iterator: 10 20 30
Elements in the vector using range-based for loop: 10 20 30
Size of the vector: 3
Capacity of the vector: 4
Is the vector empty? Yes
Experiment 12
Implement a telephone directory using files
12. Implement a telephone directory using files
Algorithm
1. Define a function addContact that takes a name and a phone number as input and appends them
to a file called telephone_directory.txt.
2. Define a function displayContacts that reads and displays all the contents of
telephone_directory.txt.
3. In the main() function, create a menu with options: "Add Contact", "Display Contacts", and
"Exit".
4. Use a loop to display the menu and take user input for the choice.
5. If the user selects "Add Contact", prompt for the name and phone number, and call the
addContact function to save the contact.
6. If the user selects "Display Contacts", call the displayContacts function to show all stored
contacts.
7. If the user selects "Exit", print a message and terminate the loop.
8. If an invalid choice is entered, prompt the user to try again.
Program
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
int main() {
int choice;
std::string name, phoneNumber;
do {
std::cout << "\nTelephone Directory Menu:\n";
std::cout << "1. Add Contact\n";
std::cout << "2. Display Contacts\n";
std::cout << "3. Exit\n";
std::cout << "Enter your choice: ";
std::cin >> choice;
switch (choice) {
case 1:
std::cout << "Enter name: ";
std::cin.ignore();
std::getline(std::cin, name);
std::cout << "Enter phone number: ";
std::getline(std::cin, phoneNumber);
addContact(name, phoneNumber);
break;
case 2:
std::cout << "Contacts in Telephone Directory:\n";
displayContacts();
break;
case 3:
std::cout << "Exiting...\n";
break;
default:
std::cout << "Invalid choice. Please enter again.\n";
}
} while (choice != 3);
return 0;
}
Output
Telephone Directory Menu:
1. Add Contact
2. Display Contacts
3. Exit
Enter your choice: 1
Enter name: bca b
Enter phone number: 9941858120
Unable to open file.
Telephone Directory Menu:
1. Add Contact
2. Display Contacts
3. Exit
Enter your choice: 2
Contacts in Telephone Directory:
Unable to open file.