0% found this document useful (0 votes)
14 views60 pages

8 To 31

dsa

Uploaded by

kartikchauhan190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views60 pages

8 To 31

dsa

Uploaded by

kartikchauhan190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

PROGRAM-8

AIM :- Write a program to enter any number and find its factorial using
constructor.
THEORY :- In this program, we create a class to calculate the factorial of a
number entered by the user. The class uses a constructor to initialize the
number and compute its factorial. A constructor is a special member
function that is automatically called when an object of the class is created.
Here, the constructor takes an integer as an argument, calculates its
factorial, and stores the result. The class also includes a member function to
display the factorial. This approach demonstrates how constructors can be
used for immediate initialization and calculations upon object creation.
CODE:-
#include <iostream>
using namespace std;
class Factorial {
int number;
long long fact; // Variable to store the factorial result
public:
// Constructor to initialize 'number' and calculate its factorial
Factorial(int n) {
number = n;
fact = 1;
for (int i = 1; i <= number; ++i) {
fact *= i;
}
}
// Function to display the factorial
void display() {
cout << "Factorial of " << number << " is: " << fact << endl;
}

1
};
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
// Creating an object of Factorial and initializing it with 'n'
Factorial f(n);
// Displaying the factorial of the number
f.display();
return 0;
}
OUTPUT:-

2
PROGRAM-9
AIM:- Write a program to generate a Fibonacci series using Copy Constructor
THEORY:- In this program, we use a copy constructor to generate a Fibonacci
series. A copy constructor initializes an object using another object of the
same class. Here, we define a class Fibonacci that contains a constructor to
initialize the length of the series and generate the Fibonacci sequence. We
then use a copy constructor to create a copy of this object, allowing us to
duplicate the generated series or perform operations on it. This approach
demonstrates the use of a copy constructor for creating new objects with the
same properties as an existing object.
CODE:-
#include <iostream>
#include <vector>
using namespace std;
class Fibonacci {
int length;
vector<int> series;
public:
// Constructor to initialize and generate the Fibonacci series
Fibonacci(int n) {
length = n;
series.push_back(0); // First element of Fibonacci series
if (n > 1) {
series.push_back(1); // Second element of Fibonacci series
for (int i = 2; i < n; ++i) {
series.push_back(series[i - 1] + series[i - 2]);
}
}
}

3
// Copy constructor
Fibonacci(const Fibonacci &f) {
length = f.length;
series = f.series;
}
// Function to display the Fibonacci series
void display() {
cout << "Fibonacci series: ";
for (int num : series) {
cout << num << " ";
}
cout << endl;
}
};
int main() {
int n;
cout << "Enter the length of the Fibonacci series: ";
cin >> n;
// Creating the first object and generating the series
Fibonacci fib1(n);
// Using the copy constructor to create a new object
Fibonacci fib2 = fib1;
// Displaying the series using both objects
cout << "Original series from fib1: ";
fib1.display();
cout << "Copied series from fib2: ";
fib2.display();

4
return 0;
}
OUTPUT:-

5
PROGRAM-13
AIM:- Write a program to find the sum of two numbers declared in a class
and display the numbers and sum using friend class.
THOERY:-
In this program, we use a friend class to find the sum of two numbers
declared in a different class. A friend class can access the private and
protected members of another class. Here, we define a class Numbers that
holds two private integer variables, x and y. Another class, Sum, is declared
as a friend of Numbers, allowing it to access Numbers' private data
members directly. The Sum class has a function to calculate the sum of the
numbers and display both the numbers and their sum.
CODE:-
#include <iostream>
using namespace std;
class Numbers; // Forward declaration of the Numbers class
class Sum {
public:
// Function to calculate and display the sum of two numbers in the Numbers class
void calculateSum(Numbers &num);
};
class Numbers {
int x, y;
public:
// Constructor to initialize x and y
Numbers(int a, int b) : x(a), y(b) {}
// Declaring Sum as a friend class to access private members of Numbers
friend class Sum;
};
// Definition of calculateSum function in Sum class
void Sum::calculateSum(Numbers &num) {
cout << "The numbers are: " << num.x << " and " << num.y << endl;
cout << "Sum of the numbers: " << num.x + num.y << endl;
}

6
int main() {
int a, b;
cout << "Enter the first number: ";
cin >> a;
cout << "Enter the second number: ";
cin >> b;
cout << endl;
// Creating an object of Numbers with user-provided values
Numbers num(a, b);
// Creating an object of Sum and calculating the sum
Sum s;
s.calculateSum(num);
return 0;
}

OUTPUT:-

7
PROGRAM-14
AIM:- Implement a class string containing the following functions:
Overload + operator to carry out the concatenation of strings.
Overload = operator to carry out string copy.
Overload <= operator to carry out the comparison of strings.
Function to display the length of a string.
Function tolower() to convert upper case letters to lower case.
Function toupper() to convert lower case letters to upper case.
THEORY:- This String class in C++ implements basic string manipulation
functions and operator overloading to mimic some functionalities similar to
those in the std::string class. The class includes:
1. Overloaded + Operator: This operator is overloaded to concatenate two
String objects. It combines the two strings and returns a new String
object containing the result.
2. Overloaded = Operator: This operator is overloaded to allow one String
object to be assigned to another, effectively copying the contents of
one String to another.
3. Overloaded <= Operator: This operator is overloaded to compare two
String objects lexicographically (alphabetical order), allowing
comparisons to determine if one string is "less than or equal to" the
other.
4. Length Function: This function returns the length of the string.
5. tolower() Function: Converts all uppercase characters in the string to
lowercase.
6. toupper() Function: Converts all lowercase characters in the string to
uppercase.
CODE:-

#include <iostream>
#include <cstring> // For strlen and strcpy functions
using namespace std;
class String {
char* str;

8
public:
// Constructor to initialize the string
String(const char* s = "") {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
// Copy constructor
String(const String &s) {
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
// Destructor
~String() {
delete[] str;
}
// Overloading + operator to concatenate strings
String operator+(const String &s) const {
char* temp = new char[strlen(str) + strlen(s.str) + 1];
strcpy(temp, str);
strcat(temp, s.str);
return String(temp);
}
// Overloading = operator to copy strings
String& operator=(const String &s) {
if (this != &s) { // Avoid self-assignment
delete[] str;

9
str = new char[strlen(s.str) + 1];
strcpy(str, s.str);
}
return *this;
}
// Overloading <= operator to compare strings
bool operator<=(const String &s) const {
return strcmp(str, s.str) <= 0;
}
// Function to display the length of the string
int length() const {
return strlen(str);
}
// Function to convert uppercase letters to lowercase
void tolower() {
for (int i = 0; str[i] != '\0'; ++i) {
if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] += 'a' - 'A';
}
}
}
// Function to convert lowercase letters to uppercase
void toupper() {
for (int i = 0; str[i] != '\0'; ++i) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] -= 'a' - 'A';

10
}
}
}
// Function to display the string
void display() const {
cout << str << endl;
}
};
int main() {
String str1("Hello"), str2(" World");
// Demonstrate concatenation using +
String str3 = str1 + str2;
cout << "Concatenated String: ";
str3.display();
// Demonstrate assignment using =
String str4;
str4 = str1;
cout << "Copied String (str4): ";
str4.display();
// Demonstrate comparison using <=
if (str1 <= str2) {
cout << "str1 is less than or equal to str2" << endl;
} else {
cout << "str1 is greater than str2" << endl;
}
// Display the length of str1

11
cout << "Length of str1: " << str1.length() << endl;
// Convert str1 to lowercase
str1.tolower();
cout << "str1 in lowercase: ";
str1.display();
// Convert str2 to uppercase
str2.toupper();
cout << "str2 in uppercase: ";
str2.display();
return 0;
}
OUTPUT:-

12
PROGRAM-10
AIM- Create a class which keep track of number of its instances. Use static
data members, constructors, and destructors to maintain updated
information about active objects.
THEORY- In this program, we define a class that keeps track of the number of
its instances. To accomplish this, we use a static data member to count the
number of active objects. Static data members are shared across all instances
of a class, making them ideal for tracking a count of all active instances. The
constructor increments the count each time a new object is created, and the
destructor decrements the count when an object is destroyed. This allows the
program to maintain an accurate count of active instances.
CODE->

#include <iostream>

using namespace std;

class InstanceCounter {

// Static data member to keep track of active instances

static int count;

public:

// Constructor to increment the instance count

InstanceCounter() {

count++;

cout << "Constructor called. Active instances: " << count << endl;

// Destructor to decrement the instance count

~InstanceCounter() {

count--;

cout << "Destructor called. Active instances: " << count << endl;

13
// Static function to access the count of active instances

static int getCount() {

return count;

};

// Initialize static data member

int InstanceCounter::count = 0;

int main() {

cout << "Initial active instances: " << InstanceCounter::getCount() << endl;

// Creating first object

InstanceCounter obj1;

cout << "Active instances after creating obj1: " << InstanceCounter::getCount() << endl;

// Creating another object

InstanceCounter obj2;

cout << "Active instances after creating obj2: " << InstanceCounter::getCount() << endl;

// Creating a temporary object within a block scope

InstanceCounter obj3;

cout << "Active instances inside block: " << InstanceCounter::getCount() << endl;

} // obj3 is destroyed here

cout << "Active instances after block: " << InstanceCounter::getCount() << endl;

return 0;

OUTPUT->

14
PROGRAM-12
AIM- Write a program to demonstrate the use of friend function with Inline
assignment.
THEORY- A friend function in C++ is a function that has special access to the
private and protected members of a class. It is not a member of the class, but
by declaring it as a friend, the class grants it access to its private data. Friend
functions are often used when an external function needs to work closely
with the class’s internal data but is not logically a member of the class.
This program demonstrates the use of a friend function with an inline
function definition. The friend function is defined inline, allowing it to
directly access and manipulate the private members of a class.
CODE-
#include <iostream>

using namespace std;

class Sample {

int value;

public:

// Constructor to initialize the value

Sample(int v) : value(v) {}

// Friend function to modify the value using inline definition

friend void increment(Sample &s);

// Function to display the value

void display() const {

cout << "Value: " << value << endl;

};

15
// Inline friend function to increment the value

inline void increment(Sample &s) {

s.value += 1;

int main() {

Sample obj(10);

cout << "Initial ";

obj.display();

// Calling the friend function to increment the value

increment(obj);

cout << "After increment ";

obj.display();

return 0;

OUTPUT->

16
PROGRAM-11
AIM- Write a program to find the biggest of three number using Friend
Function.
THEORY- In this program, we use a friend function to find the largest of three
numbers. A friend function in C++ is declared with the keyword friend inside
a class, allowing it access to the private members of that class. Although the
friend function is not a class member, it can directly access and manipulate
the class’s private data.
Here, we create a class Number that holds three private integer values. A
friend function named Find Max is used to access these values and determine
the largest among them.
CODE->
#include <iostream>

using namespace std;

class Numbers {

int num1, num2, num3;

public:

// Constructor to initialize the three numbers

Numbers(int a, int b, int c) : num1(a), num2(b), num3(c) {}

// Friend function declaration to find the maximum of three numbers

friend int findMax(Numbers n);

};

// Friend function to find the largest of three numbers

int findMax(Numbers n) {

int max = n.num1;

if (n.num2 > max) {

max = n.num2;

if (n.num3 > max) {

max = n.num3;

17
}

return max;

int main() {

int a, b, c;

cout << "Enter three numbers: ";

cin >> a >> b >> c;

// Create an instance of Numbers

Numbers nums(a, b, c);

// Find and display the largest number

cout << "The largest number is: " << findMax(nums) << endl;

return 0;

OUTPUT->

18
PROGRAM 15
AIM- Write a program to overload unary increment (++) operator.
THEORY-
In this program, we demonstrate overloading the unary increment operator +
+ in C++. Operator overloading allows us to define custom behavior for
operators when used with user-defined types (classes). The unary increment
operator (++) can be overloaded in two forms:
1. Prefix Increment: ++obj - Increments the value of the object before it is
used in an expression.
2. Postfix Increment: obj++ - Uses the object's value in an expression
before incrementing it.
CODE->
#include <iostream>

using namespace std;

class Counter {

int value;

public:

// Constructor to initialize the counter value

Counter(int v = 0) : value(v) {}

// Overloading prefix increment (i.e., ++obj)

Counter& operator++() {

++value;

return *this;

// Overloading postfix increment (i.e., obj++)

Counter operator++(int) {

Counter temp = *this; // Save the current state

19
value++;

return temp;

// Function to display the current value

void display() const {

cout << "Value: " << value << endl;

};

int main() {

Counter obj(10);

cout << "Initial ";

obj.display();

// Using prefix increment

++obj;

cout << "After prefix increment ";

obj.display();

// Using postfix increment

obj++;

cout << "After postfix increment ";

obj.display();

return 0;

OUTPUT->

20
PROGRAM 16
AIM- Write a program to overload new and delete operator.
THEORY- In C++, the new and delete operators can be overloaded to define
custom memory allocation and deallocation behavior for a class. Overloading
these operators allows us to control how memory is allocated and released
for objects of that class. This can be useful in cases where we want to
optimize memory usage, track memory allocation, or perform specific
initialization or cleanup actions.
The new operator is used to allocate memory, while the delete operator is
used to deallocate memory. Overloading these operators allows us to add
custom behavior, such as logging or special memory management
techniques, when objects of a class are created and destroyed.
CODE-
#include <iostream>

#include <cstdlib> // For malloc and free

using namespace std;

class CustomMemory {

int data;

public:

CustomMemory(int val = 0) : data(val) {

cout << "Constructor called, data = " << data << endl;

~CustomMemory() {

cout << "Destructor called, data = " << data << endl;

// Overloading new operator

void* operator new(size_t size) {

cout << "Overloaded new operator, size: " << size << endl;

21
void* ptr = malloc(size); // Allocate memory

if (!ptr) {

throw bad_alloc(); // If memory allocation fails, throw an exception

return ptr;

// Overloading delete operator

void operator delete(void* ptr) {

cout << "Overloaded delete operator" << endl;

free(ptr); // Deallocate memory

// Display the data

void display() const {

cout << "Data: " << data << endl;

};

int main() {

cout << "Creating object using overloaded new operator..." << endl;

CustomMemory* obj = new CustomMemory(42); // Using overloaded new

obj->display();

cout << "Deleting object using overloaded delete operator..." << endl;

delete obj; // Using overloaded delete

return 0;

OUTPUT->

22
PROGRAM 17
AIM- Create class first with data members book no, book name and member
function getdata and putdata. Create a class second with data members
author name, publisher and members getdata and showdata. Derive a class
third from first and second with data member no of pages and year of
publication. Display all this information using array of objects of third class.
(Multiple Inheritance)
THOERY->
In this program, we are demonstrating multiple inheritance in C++, where the
derived class Third inherits data members and functions from two base
classes, First and Second. The base class First contains book details such as
the book number and book name, while the base class Second holds the
author's name and publisher. The derived class Third adds two more data
members: the number of pages and year of publication. An array of Third
class objects is used to display all information about the books.
CODE->
#include <iostream>

using namespace std;

class First {

protected:

int book_no;

string book_name;

public:

void getdata() {

cout << "Enter book number: ";

cin >> book_no;

cout << "Enter book name: ";

cin >> book_name;

void putdata() {

cout << "Book Number: " << book_no << endl;

cout << "Book Name: " << book_name << endl;

23
}

};

class Second {

protected:

string author_name;

string publisher;

public:

void getdata() {

cout << "Enter author name: ";

cin >> author_name;

cout << "Enter publisher: ";

cin >> publisher;

void showdata() {

cout << "Author Name: " << author_name << endl;

cout << "Publisher: " << publisher << endl;

};

class Third : public First, public Second {

protected:

int no_of_pages;

int year_of_publication;

public:

void getdata() {

First::getdata();

Second::getdata();

cout << "Enter number of pages: ";

cin >> no_of_pages;

cout << "Enter year of publication: ";

cin >> year_of_publication;

24
}

void showdata() {

First::putdata();

Second::showdata();

cout << "Number of Pages: " << no_of_pages << endl;

cout << "Year of Publication: " << year_of_publication << endl;

};

int main() {

int n;

cout << "Enter the number of books: ";

cin >> n;

Third books[n]; // Array of objects of class Third

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

cout << "\nEnter details for book " << i + 1 << ":\n";

books[i].getdata();

cout << "\nDisplaying Book Information:\n";

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

cout << "\nBook " << i + 1 << " Details:\n";

books[i].showdata();

return 0;

25
OUTPUT->

26
PROGRAM 18
AIM-> Design three classes STUDENT, EXAM, and RESULT. The STUDENT class
has data members such as roll no, name. Create a class EXAM by inheriting
the STUDENT class. The EXAM class adds data members representing the
marks scored in six subjects. Derive the RESULT from the EXAM class and has
its own data members such as total marks. WAP to model this relationship.
THEORY->
In this example, we implement multilevel inheritance where the EXAM class
inherits from the STUDENT class, and the RESULT class inherits from the
EXAM class. The STUDENT class holds basic student information, EXAM adds
marks for six subjects, and RESULT calculates the total marks and displays the
result.
CODE->
#include <iostream>

using namespace std;

class STUDENT {

protected:

int roll_no;

string name;

public:

void getdata() {

cout << "Enter roll number: ";

cin >> roll_no;

cout << "Enter student name: ";

cin >> name;

void putdata() {

cout << "Roll Number: " << roll_no << endl;

27
cout << "Student Name: " << name << endl;

};

class EXAM : public STUDENT {

protected:

int marks[6];

public:

void getdata() {

STUDENT::getdata();

cout << "Enter marks for 6 subjects: ";

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

cin >> marks[i];

void putdata() {

STUDENT::putdata();

cout << "Marks in 6 subjects: ";

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

cout << marks[i] << " ";

cout << endl;

};

class RESULT : public EXAM {

int total_marks;

public:

28
void calculate() {

total_marks = 0;

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

total_marks += marks[i];

void display() {

EXAM::putdata();

calculate();

cout << "Total Marks: " << total_marks << endl;

};

int main() {

RESULT student_result;

student_result.getdata();

student_result.display();

return 0;

OUTPUT->

29
PROGRAM 19
AIM:- Create a base class called SHAPE. Use this class to store two double type values. Derive two
specific classes called TRIANGLE and RECTANGLE from the base class. Add to the base class, a
member function getdata to initialize base class data members and another member function
display to compute and display the area of figures. Make display a virtual function and redefine
this function in the derived classes to suit their requirements. Using these three classes design a
program that will accept driven of a TRIANGLE or RECTANGLE interactively and display the area.

THEORY-> In this example, we demonstrate the use of virtual functions in C++. A base class SHAPE
stores two double-type values representing the dimensions of a shape. The derived classes
TRIANGLE and RECTANGLE inherit from SHAPE and redefine a virtual function display() to compute
and display the area of the shape. The virtual function allows polymorphic behavior, enabling the
correct display() function to be called based on the type of object at runtime.

CODE->

#include <iostream>

#include <cmath> // For area calculation of triangle

using namespace std;

class SHAPE {

protected:

double dimension1, dimension2;

public:

void getdata(double d1, double d2) {

dimension1 = d1;

dimension2 = d2;

virtual void display() {

cout << "Area: " << 0 << endl;

};

class TRIANGLE : public SHAPE {

public:

30
void display() override {

double area = 0.5 * dimension1 * dimension2;

cout << "Area of Triangle: " << area << endl;

};

class RECTANGLE : public SHAPE {

public:

void display() override {

double area = dimension1 * dimension2;

cout << "Area of Rectangle: " << area << endl;

};

int main() {

SHAPE* shape;

TRIANGLE triangle;

RECTANGLE rectangle;

// Input data for triangle

cout << "Enter base and height of Triangle: ";

double base, height;

cin >> base >> height;

triangle.getdata(base, height);

// Input data for rectangle

cout << "Enter length and width of Rectangle: ";

double length, width;

cin >> length >> width;

rectangle.getdata(length, width);

31
// Polymorphism in action

shape = &triangle;

shape->display();

shape = &rectangle;

shape->display();

return 0;

OUTPUT->

32
PROGRAM 20
AIM->Create a class called LIST with two pure virtual functions store() and
retrieve(). To store a value call store and to retrieve call retrieve function.
Derive two classes stack and queue from it and override store and retrieve.
THEORY->we create an abstract class LIST that has two pure virtual functions:
store() and retrieve(). These functions will be used to store and retrieve
values in different ways depending on the derived class. We will then create
two derived classes, stack and queue, that provide specific implementations
of store() and retrieve().
In a stack, the data follows the Last In, First Out (LIFO) principle, meaning the
last element stored is the first to be retrieved. The store() function in a stack
will push a value onto the stack, while retrieve() will pop the last value
added.
In a queue, the data follows the First In, First Out (FIFO) principle, meaning
the first element stored is the first to be retrieved. The store() function in a
queue will enqueue a value at the end, and retrieve() will dequeue the first
value added.
CODE->
#include <iostream>

#include <vector>

#include <stdexcept>

class LIST {

public:

virtual void store(int value) = 0; // Pure virtual function for storing a value

virtual int retrieve() = 0; // Pure virtual function for retrieving a value

virtual ~LIST() {} // Virtual destructor for safe polymorphic behavior

};

class Stack : public LIST {

private:

std::vector<int> data;

33
public:

void store(int value) override {

data.push_back(value); // Store value by adding to the end of the stack

int retrieve() override {

if (data.empty()) {

throw std::out_of_range("Stack is empty");

int value = data.back();

data.pop_back(); // Remove the last element (LIFO)

return value;

};

class Queue : public LIST {

private:

std::vector<int> data;

public:

void store(int value) override {

data.push_back(value); // Store value by adding to the end of the queue

int retrieve() override {

if (data.empty()) {

throw std::out_of_range("Queue is empty");

int value = data.front();

data.erase(data.begin()); // Remove the first element (FIFO)

return value;

34
};

int main() {

LIST* stack = new Stack();

stack->store(1);

stack->store(2);

stack->store(3);

std::cout << "Stack retrieve: " << stack->retrieve() << std::endl; // Should print 3 (LIFO)

LIST* queue = new Queue();

queue->store(1);

queue->store(2);

queue->store(3);

std::cout << "Queue retrieve: " << queue->retrieve() << std::endl; // Should print 1 (FIFO)

delete stack;

delete queue;

return 0;

OUTPUT->

35
PROGRAM 21
AIM-> Write a program to define the function template for calculating the square of given
numbers with different data types.

THEORY-> A function template in C++ allows the creation of a single function that can operate on
different data types. By defining a template with a type parameter, the compiler generates a
specific instance of the function for each data type used. Here, we define a template function
square() that takes a single argument and returns its square. The template uses T as a generic
placeholder, allowing square() to be used with any numeric data type. This approach improves
code efficiency, reducing the need to write separate functions for each type.

CODE->

#include <iostream>

using namespace std;

template <typename T>

T square(T num) {

return num * num;

int main() {

int intNum = 5;

double doubleNum = 4.5;

cout << "Square of " << intNum << " is " << square(intNum) << endl;

cout << "Square of " << doubleNum << " is " << square(doubleNum) << endl;

return 0;

OUTPUT->

36
PROGRAM 22
AIM-> Write a program to define the function template for swapping two
items of various datatypes such as integers, float, and characters.
THEORY-> A function template provides a way to define a generic function
that works with multiple data types. Here, we create a template function
swapValues() that takes two references of the same type T as parameters.
The function then swaps the values of these two variables. The template
enables swapValues() to work with integers, floats, characters, and more
without rewriting the function for each type.
CODE->
#include <iostream>

using namespace std;

// Function template to swap two values of any data type

template <typename T>

void swapValues(T &a, T &b) {

T temp = a;

a = b;

b = temp;

int main() {

int intA = 10, intB = 20;

float floatA = 5.5, floatB = 10.5;

char charA = 'X', charB = 'Y';

cout << "Before swapping:\n";

cout << "intA = " << intA << ", intB = " << intB << endl;

cout << "floatA = " << floatA << ", floatB = " << floatB << endl;

cout << "charA = " << charA << ", charB = " << charB << endl;

37
// Swapping integers

swapValues(intA, intB);

// Swapping floats

swapValues(floatA, floatB);

// Swapping characters

swapValues(charA, charB);

cout << "\nAfter swapping:\n";

cout << "intA = " << intA << ", intB = " << intB << endl;

cout << "floatA = " << floatA << ", floatB = " << floatB << endl;

cout << "charA = " << charA << ", charB = " << charB << endl;

return 0;

OUTPUT->

38
PROGRAM 23
AIM-> Write a program to illustrate how Template function can be overloaded
THEORY-> Function Template Overloading: Overloading a function template
means defining multiple versions of a function with the same name but with
different parameter lists. The compiler chooses the appropriate version based
on the argument types passed to the function. By combining templates and
overloading, we can create versatile functions that handle specific types in
unique ways.
CODE->
#include <iostream>

#include <string>

using namespace std;

// General template for displaying any type of value

template <typename T>

void display(T value) {

cout << "Generic Display: " << value << endl;

// Overloaded template specifically for integer type

template <>

void display(int value) {

cout << "Integer Display: " << value << endl;

// Overloaded template specifically for floating-point type

template <>

void display(float value) {

cout << "Float Display: " << value << endl;

39
// Overloaded template specifically for string type

template <>

void display(string value) {

cout << "String Display: " << value << endl;

int main() {

display(42); // Calls the integer-specific overload

display(3.14f); // Calls the float-specific overload

display("Hello"); // Calls the string-specific overload

display(3.14159); // Calls the generic template (for double)

return 0;

OUTPUT->

40
PROGRAM 24
AIM-> Write a program to demonstrate the use of special functions,
constructor, and destructor in the class template. The program is used to find
the bigger of two entered numbers
THEORY-> In C++, special functions include the constructor and destructor. A
constructor initializes objects when they are created, while a destructor is
automatically called when the object goes out of scope, allowing you to
release resources or perform cleanup operations. By utilizing a class
template, we can generalize the process of finding the larger number for
different data types (such as integers, floats, etc.).
CODE->
#include <iostream>

using namespace std;

// Template class to find the larger of two numbers

template <typename T>

class Compare {

private:

T num1, num2;

public:

// Constructor to initialize the numbers

Compare(T n1, T n2) {

num1 = n1;

num2 = n2;

cout << "Constructor: Numbers initialized." << endl;

// Destructor

~Compare() {

cout << "Destructor: Object is being destroyed." << endl;

41
}

// Function to find and return the larger of the two numbers

T findLarger() {

return (num1 > num2) ? num1 : num2;

};

int main() {

int a = 10, b = 20;

float x = 5.5f, y = 3.3f;

// Create an object of Compare with integers

Compare<int> intCompare(a, b);

cout << "Larger of " << a << " and " << b << " is: " << intCompare.findLarger() << endl;

// Create an object of Compare with floats

Compare<float> floatCompare(x, y);

cout << "Larger of " << x << " and " << y << " is: " << floatCompare.findLarger() << endl;

return 0;

OUTPUT->

42
PROGRAM 25
AIM-> Write a program to illustrate how to define and declare a class
template for reading two data items from the keyboard and to find their sum.
THEORY-> A class template allows us to create a generic class that can work
with any data type. In this program, the class template will define two data
members to store the two input values. The class will also have a member
function to read values from the user and another function to compute and
display the sum of these values.
CODE->
#include <iostream>

using namespace std;

// Class template to read two data items and find their sum

template <typename T>

class SumCalculator {

private:

T num1, num2; // Two data members to store the numbers

public:

// Member function to read two numbers from the keyboard

void readData() {

cout << "Enter first number: ";

cin >> num1;

cout << "Enter second number: ";

cin >> num2;

// Member function to calculate and return the sum

T findSum() {

return num1 + num2;

43
};

int main() {

// Create an object for the SumCalculator template with int type

SumCalculator<int> intSum;

intSum.readData();

cout << "Sum of the two integers: " << intSum.findSum() << endl;

// Create an object for the SumCalculator template with float type

SumCalculator<float> floatSum;

floatSum.readData();

cout << "Sum of the two floats: " << floatSum.findSum() << endl;

return 0;

OUTPUT->

44
PROGRAM 26
AIM-> Write a program to perform the deletion of white spaces such as
horizontal tab, vertical tab, space, line feed, new line and carriage return
from a text file and store the contents of the file without the white spaces on
another file.
THEORY-> Whitespace characters in a text file, such as space, horizontal tab (\
t), vertical tab (\v), line feed (\n), new line (\r), and carriage return (\r), are
often used for formatting but may need to be removed in certain situations.
The task here is to read an input text file, remove these whitespace
characters, and save the modified content to a new output file.
CODE->
#include <iostream>

#include <fstream>

#include <cctype> // For checking whitespace characters

// Function to remove all whitespace characters from a file

void removeWhiteSpaces(const std::string& inputFileName, const std::string& outputFileName) {

std::ifstream inputFile(inputFileName); // Open the input file

if (!inputFile) {

std::cerr << "Error opening input file." << std::endl;

return;

std::ofstream outputFile(outputFileName); // Open the output file

if (!outputFile) {

std::cerr << "Error opening output file." << std::endl;

return;

char ch;

// Read each character from the input file

45
while (inputFile.get(ch)) {

// Check if the character is not a whitespace character (excluding space, tab, newline, etc.)

if (!std::isspace(ch)) {

outputFile.put(ch); // Write the character to the output file if it's not a whitespace

// Close the files

inputFile.close();

outputFile.close();

std::cout << "Whitespace removed and saved to " << outputFileName << std::endl;

int main() {

std::string inputFileName = "input.txt"; // Input file name

std::string outputFileName = "output.txt"; // Output file name

// Call function to remove white spaces from the input file

removeWhiteSpaces(inputFileName, outputFileName);

return 0;

OUTPUT->

46
PROGRAM 27
AIM-> Write a program to read a set of lines from the keyboard and to store it
on a specified file.
THEORY->
To read a set of lines from the keyboard and store them in a specified file, we
can use the file handling features provided by C++. The process involves:
1. Reading lines from the user using the std::getline() function.
2. Opening an output file using std::ofstream.
3. Writing the input lines to the file until the user signals that they have
finished (e.g., by entering a special keyword or pressing EOF).
4. Closing the file after writing the lines.

CODE->
#include <iostream>

#include <fstream>

#include <string>

// Function to read lines from the keyboard and store them in a specified file

void storeLinesInFile(const std::string& fileName) {

std::ofstream outFile(fileName); // Open the file in write mode

if (!outFile) {

std::cerr << "Error opening file for writing!" << std::endl;

return;

std::string line;

std::cout << "Enter lines of text (type 'END' to stop):" << std::endl;

// Keep reading lines from the user until "END" is typed

while (true) {

std::getline(std::cin, line); // Read a line from the keyboard

if (line == "END") {

break; // Stop input if the user types "END"

47
}

outFile << line << std::endl; // Write the line to the file

outFile.close(); // Close the file

std::cout << "Lines have been written to the file " << fileName << std::endl;

int main() {

std::string fileName;

std::cout << "Enter the file name to store the lines: ";

std::getline(std::cin, fileName); // Get the file name from the user

storeLinesInFile(fileName); return 0;}

OUTPUT->

48
PROGRAM 28
AIM-> Write a program to read the class object of student info such as name,
age, sex, height and weight from the keyboard and to store them on a
specified file using read() and write() functions. Again, the same file is opened
for reading and displaying the contents of the file on the screen.
THEORY->creating a class for storing student information, such as name, age,
sex, height, and weight. The data is to be input from the keyboard, stored in a
file using write() and read() functions, and then displayed by reading the
contents of the file back to the screen.
CODE->
#include <iostream>

#include <fstream>

#include <string>

using namespace std;

class Student {

private:

string name;

int age;

char sex;

float height;

float weight;

public:

// Function to input data

void getData() {

cout << "Enter Name: ";

cin.ignore(); // Ignore the newline left in the input buffer

getline(cin, name);

49
cout << "Enter Age: ";

cin >> age;

cout << "Enter Sex (M/F): ";

cin >> sex;

cout << "Enter Height (in meters): ";

cin >> height;

cout << "Enter Weight (in kg): ";

cin >> weight;

// Function to store data to file

void writeToFile() {

ofstream outFile("studentData.dat", ios::binary);

if (!outFile) {

cerr << "Error opening file for writing!" << endl;

return;

outFile.write(reinterpret_cast<char*>(this), sizeof(*this));

outFile.close();

// Function to read data from file

void readFromFile() {

ifstream inFile("studentData.dat", ios::binary);

if (!inFile) {

cerr << "Error opening file for reading!" << endl;

return;

50
}

inFile.read(reinterpret_cast<char*>(this), sizeof(*this));

inFile.close();

// Function to display data

void display() {

cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

cout << "Sex: " << sex << endl;

cout << "Height: " << height << " meters" << endl;

cout << "Weight: " << weight << " kg" << endl;

};

int main() {

Student student;

// Get student data from user

student.getData();

// Store the data into a file

student.writeToFile();

// Read the data back from the file

Student anotherStudent;

anotherStudent.readFromFile();

// Display the data from the file

cout << "\nStudent Data from the file:" << endl;

51
anotherStudent.display();

return 0;

OUTPUT->

52
PROGRAM 29
AIM-> Write a program to read a text file and display its contents on the
screen.
THEORY-> In C++, reading the contents of a text file and displaying it on the
screen is a basic operation that demonstrates file input using ifstream (input
file stream). The process involves:
1. Opening a File: Using ifstream to open a file in read mode.
2. Reading Data: We read the data from the file using methods like
getline() or the extraction operator (>>), depending on the file
structure.
3. Displaying Contents: After reading the contents, we output it to the
console using cout.
4. Closing the File: After reading the file, it's important to close it using
close().
CODE->
#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main() {

// Create an object of ifstream to read the file

ifstream inputFile("sample.txt");

// Check if the file was opened successfully

if (!inputFile) {

cerr << "Error opening the file!" << endl;

return 1; // Exit the program if the file can't be opened

53
string line;

// Read the file line by line

while (getline(inputFile, line)) {

// Display each line

cout << line << endl;

// Close the file after reading

inputFile.close();

return 0;

OUTPUT->

54
PROGRAM 30
AIM-> Write a program to copy the contents of a file into another.
THEORY-> To copy the contents of one file to another, we can use file input
and output streams in C++. The program will:
1. Open the source file (input.txt) in read mode using std::ifstream.
2. Open the destination file (output.txt) in write mode using
std::ofstream.
3. Read the contents of the source file and write it directly to the
destination file.
4. Close both files after the operation is complete.

CODE->
#include <iostream>

#include <fstream>

#include <string>

using namespace std;

void copyFileContents(const string& sourceFile) {

string destinationFile = "output.txt"; // Predefined destination file name

ifstream inputFile(sourceFile, ios::binary); // Open the source file in binary mode

if (!inputFile) { // Check if the source file was successfully opened

cerr << "Error opening source file!" << endl;

return;

ofstream outputFile(destinationFile, ios::binary); // Open the destination file in binary mode

if (!outputFile) { // Check if the destination file was successfully opened

cerr << "Error opening destination file!" << endl;

return;

char ch;

// Read each character from the source file and write it to the destination file

55
while (inputFile.get(ch)) {

outputFile.put(ch);

inputFile.close(); // Close the source file

outputFile.close(); // Close the destination file

cout << "File copied successfully from " << sourceFile << " to " << destinationFile << endl;

int main() {

string sourceFile;

// Get the source file name from the user

cout << "Enter the source file name: ";

cin >> sourceFile;

// Call the function to copy the file contents

copyFileContents(sourceFile);

return 0;

OUTPUT->

PROGRAM 31

56
AIM-> Write a program to raise an exception if any attempt is made to refer
to an element whose index is beyond the array size
THEORY-> In C++, exceptions are handled using the try, catch, and throw
keywords. To raise an exception when an invalid index is accessed in an array,
we can do the following:
1. Define an array and attempt to access an element using an index.
2. Use an if condition to check whether the index is within the valid
bounds of the array.
3. If the index is invalid (i.e., greater than or equal to the size of the array
or less than 0), throw an exception.
4. Catch the exception using a try-catch block and display an error
message.
CODE->
#include <iostream>

#include <stdexcept> // For exception handling

using namespace std;

// Function to access an element from the array and raise exception if index is out of bounds

void accessElement(int arr[], int size, int index) {

// Check if the index is within the valid range

if (index < 0 || index >= size) {

throw out_of_range("Index out of bounds"); // Throw an exception if index is invalid

cout << "Element at index " << index << ": " << arr[index] << endl; // Access and print the element

int main() {

int arr[] = {10, 20, 30, 40, 50}; // An array of 5 integers

int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

57
int index;

cout << "Enter the index of the element to access: ";

cin >> index;

try {

// Attempt to access the element at the specified index

accessElement(arr, size, index);

} catch (const out_of_range& e) {

// Catch the exception if the index is out of bounds and display an error message

cout << "Error: " << e.what() << endl;

return 0;

OUTPUT->

58
PROGRAM 32
AIM-> Write a program to read two numbers and then divide first no by
second no and raise an exception if second number is zero.
THOERY-> In C++, division by zero can lead to a runtime error, which can be
avoided using exceptions. The try-catch mechanism is used to handle such
errors. In the try block, the division operation is attempted, and if the second
number is zero, a throw statement generates an exception. The catch block
then handles the exception, preventing the program from crashing and
providing a user-friendly message or alternate behavior. This method ensures
the program remains robust and continues running smoothly even in the case
of unexpected inputs.
CODE->
#include <iostream>

#include <stdexcept> // For exception handling

using namespace std;

// Function to divide two numbers and raise exception if divisor is zero

double divide(double num1, double num2) {

if (num2 == 0) {

throw runtime_error("Error: Division by zero is not allowed.");

return num1 / num2; // Return the result of division if valid

int main() {

double num1, num2;

// Take input from the user

cout << "Enter the first number: ";

cin >> num1;

cout << "Enter the second number: ";

59
cin >> num2;

try {

// Attempt to divide the numbers

double result = divide(num1, num2);

cout << "The result of " << num1 << " / " << num2 << " is: " << result << endl;

} catch (const runtime_error& e) {

// Catch the exception if division by zero is attempted

cout << e.what() << endl;

return 0;

OUTPUT->

60

You might also like