8 To 31
8 To 31
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>
class InstanceCounter {
public:
InstanceCounter() {
count++;
cout << "Constructor called. Active instances: " << count << endl;
~InstanceCounter() {
count--;
cout << "Destructor called. Active instances: " << count << endl;
13
// Static function to access the count of active instances
return count;
};
int InstanceCounter::count = 0;
int main() {
cout << "Initial active instances: " << InstanceCounter::getCount() << endl;
InstanceCounter obj1;
cout << "Active instances after creating obj1: " << InstanceCounter::getCount() << endl;
InstanceCounter obj2;
cout << "Active instances after creating obj2: " << InstanceCounter::getCount() << endl;
InstanceCounter obj3;
cout << "Active instances inside block: " << InstanceCounter::getCount() << endl;
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>
class Sample {
int value;
public:
Sample(int v) : value(v) {}
};
15
// Inline friend function to increment the value
s.value += 1;
int main() {
Sample obj(10);
obj.display();
increment(obj);
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>
class Numbers {
public:
};
int findMax(Numbers n) {
max = n.num2;
max = n.num3;
17
}
return max;
int main() {
int a, b, c;
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>
class Counter {
int value;
public:
Counter(int v = 0) : value(v) {}
Counter& operator++() {
++value;
return *this;
Counter operator++(int) {
19
value++;
return temp;
};
int main() {
Counter obj(10);
obj.display();
++obj;
obj.display();
obj++;
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>
class CustomMemory {
int data;
public:
cout << "Constructor called, data = " << data << endl;
~CustomMemory() {
cout << "Destructor called, data = " << data << endl;
cout << "Overloaded new operator, size: " << size << endl;
21
void* ptr = malloc(size); // Allocate memory
if (!ptr) {
return ptr;
};
int main() {
cout << "Creating object using overloaded new operator..." << endl;
obj->display();
cout << "Deleting object using overloaded delete operator..." << endl;
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>
class First {
protected:
int book_no;
string book_name;
public:
void getdata() {
void putdata() {
23
}
};
class Second {
protected:
string author_name;
string publisher;
public:
void getdata() {
void showdata() {
};
protected:
int no_of_pages;
int year_of_publication;
public:
void getdata() {
First::getdata();
Second::getdata();
24
}
void showdata() {
First::putdata();
Second::showdata();
};
int main() {
int n;
cin >> n;
cout << "\nEnter details for book " << i + 1 << ":\n";
books[i].getdata();
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>
class STUDENT {
protected:
int roll_no;
string name;
public:
void getdata() {
void putdata() {
27
cout << "Student Name: " << name << endl;
};
protected:
int marks[6];
public:
void getdata() {
STUDENT::getdata();
void putdata() {
STUDENT::putdata();
};
int total_marks;
public:
28
void calculate() {
total_marks = 0;
total_marks += marks[i];
void display() {
EXAM::putdata();
calculate();
};
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>
class SHAPE {
protected:
public:
dimension1 = d1;
dimension2 = d2;
};
public:
30
void display() override {
};
public:
};
int main() {
SHAPE* shape;
TRIANGLE triangle;
RECTANGLE rectangle;
triangle.getdata(base, height);
rectangle.getdata(length, width);
31
// Polymorphism in action
shape = ▵
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
};
private:
std::vector<int> data;
33
public:
if (data.empty()) {
return value;
};
private:
std::vector<int> data;
public:
if (data.empty()) {
return value;
34
};
int main() {
stack->store(1);
stack->store(2);
stack->store(3);
std::cout << "Stack retrieve: " << stack->retrieve() << std::endl; // Should print 3 (LIFO)
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>
T square(T num) {
int main() {
int intNum = 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>
T temp = a;
a = b;
b = temp;
int main() {
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 << "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>
template <>
template <>
39
// Overloaded template specifically for string type
template <>
int main() {
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>
class Compare {
private:
T num1, num2;
public:
num1 = n1;
num2 = n2;
// Destructor
~Compare() {
41
}
T findLarger() {
};
int main() {
cout << "Larger of " << a << " and " << b << " is: " << intCompare.findLarger() << endl;
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>
// Class template to read two data items and find their sum
class SumCalculator {
private:
public:
void readData() {
T findSum() {
43
};
int main() {
SumCalculator<int> intSum;
intSum.readData();
cout << "Sum of the two integers: " << intSum.findSum() << endl;
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>
if (!inputFile) {
return;
if (!outputFile) {
return;
char ch;
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
inputFile.close();
outputFile.close();
std::cout << "Whitespace removed and saved to " << outputFileName << std::endl;
int main() {
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
if (!outFile) {
return;
std::string line;
std::cout << "Enter lines of text (type 'END' to stop):" << std::endl;
while (true) {
if (line == "END") {
47
}
outFile << line << std::endl; // Write the line to 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: ";
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>
class Student {
private:
string name;
int age;
char sex;
float height;
float weight;
public:
void getData() {
getline(cin, name);
49
cout << "Enter Age: ";
void writeToFile() {
if (!outFile) {
return;
outFile.write(reinterpret_cast<char*>(this), sizeof(*this));
outFile.close();
void readFromFile() {
if (!inFile) {
return;
50
}
inFile.read(reinterpret_cast<char*>(this), sizeof(*this));
inFile.close();
void display() {
cout << "Height: " << height << " meters" << endl;
cout << "Weight: " << weight << " kg" << endl;
};
int main() {
Student student;
student.getData();
student.writeToFile();
Student anotherStudent;
anotherStudent.readFromFile();
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>
int main() {
ifstream inputFile("sample.txt");
if (!inputFile) {
53
string line;
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>
return;
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);
cout << "File copied successfully from " << sourceFile << " to " << destinationFile << endl;
int main() {
string sourceFile;
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>
// Function to access an element from the array and raise exception if index is out of bounds
cout << "Element at index " << index << ": " << arr[index] << endl; // Access and print the element
int main() {
57
int index;
try {
// Catch the exception if the index is out of bounds and display an error message
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>
if (num2 == 0) {
int main() {
59
cin >> num2;
try {
cout << "The result of " << num1 << " / " << num2 << " is: " << result << endl;
return 0;
OUTPUT->
60