Vous êtes sur la page 1sur 183

Object Oriented Programming Using C++

SESSION:-2016-17

Name:-P.H.Bharadwaj Submitted to-Seema Mehla


Section :-IT-1
Rollno.:-11510470
INDEX

Sr No. EXPERIMENT DATE PAGE NO.


1.I A phone number, such as (212) 767-8900, can be thought
of as having three parts: the area code (212), the exchange
(767), and the number (8900). Write a program that uses a
structure to store these three parts of a phone number
separately. Call the structure phone. Create two structure
variables of type phone. Initialize one, and have the user
input a number for the other one. Then display both
numbers. The interchange might look like this:

1.II A point on the two-dimensional plane can be represented


by two numbers: an X coordinate and Y coordinate. For
example, (4,5) represents a point 4 units to the right of the
origin along the X axis, and 5 units up the Y axis. The sum
of two points can be defined as a new point whose X
coordinate is the sum of the X coordinates of the two
points, and whose Y coordinate is the sum of their Y
coordinates.
Write a program that uses a structure called point to
model a point. Define three points, and have the user
input values to two of them. Then set the third point equal
to the sum of the other two, and display the value of the
new point.
1.III Write a program to create a structure, Employee,
having following attributes-
Private data:
Employee_name, Employee_id, Employee_salary,
Employee_address
Write a main program to take employee’s information
and print the same.
2.I Write a program to create a class, Employee having
following attributes-
Private data:
Employee_name, Employee_id, Employee_salary,
Employee_address
Public methods :
getInput();
PrintOutput();
Write a main program to test it.
2.II Create a class that initiates part of functionality of the
basic data type int. Call the class Int(note different
spelling). The only data in this class is an int variable.
Include member functions to initialize an Int to 0, to
initialize it to an int value, to display it( looks just like
an int), and to add two Int values. Write a program that
exercises this class by creating two initialized and one
uninitialized Int values, adding these two initialized
values and placing the response in the uninitialized
value, and then displaying this result.
2.III Define a class to represent a bank account. Include the
following members:
Data Members: Name of the depositor, Account no. ,
Type of account, Balance amount.
Member Functions: To assign initial values,
To deposit an amount,To withdraw an amount
after checking the balance,
To display name and balance.
Write a main program to test the program.

2.IV Imagine a tollbooth at a bridge. Cars passing by the


booth are expected to pay a fifty-cent toll. Mostly they
do, but sometimes a car goes by without paying. The
tollbooth keeps track of the number of cars that have
gone by, and of the total amount of money collected.
Model this tollbooth with a class called TollBooth.
The two data items are a type unsigned int to hold the
total number of cars, and a type double to hold the
total number of cars, and a type double to hold the
total amount of money collected. An initialization
function sets both these values to 0. A member
function called payingCar() increments the car total
and adds 0.50 to the cash total. Another function,
called nopayCar(), increments the car total but adds
nothing to the cash total. Finally, a member function
called display() desplays the two totals.
Include a program to test this class. This program
shold allow the user to push one key to count a paying
car, and another to count a nonpaying car. Pusing the
ESC key should cause the program to print out the
total cars and total cash and then exit.
3.I Create a class called Employee that contains a name
(an array of char) and an employee number (type
long). Include a member function called getData() to
get data from the user for insertion into the object, and
another function called putData() to display the data.
Assume the name has no embedded banks.
Write a main() program to exercise this class. It should
create an array of type employee, and then invite the
user to input data for up to 100 employees. Finally, it
should print out the data for all the employees.
3.II Create the database of students using Class, having the
following attributes :
roll_no, student_name, student_address, student_city,
student_pin, student_sem, rank, and
branch. Also write the program to enter the data for
500 students in any order and then display the list of
students for a given branch and semester on display.

3.III Write a program that calculates the average of up to


100 English distances input by the user. Create an
array of objects of the Distance class. To calculate the
average, you can create dist_add() method, that
perform addition over 100 distance’s object. You will
also need a member function that divides a Distance
value by an integer. A brief description of class
Distance is given below.
class Distance
{
private:
int feet;
float inches;
public:
void getDist();
void showDist();
};

4.I Create a class called Time that has separate int


member data for hours, minutes, and seconds. One
constructor should initialize this data to 0, and another
should initialize it to fixed values. A member function
should add two objects of type time passed as
arguments. A main() program should create two
initialized time objects, and one that isn’t initialized.
The it should add the two initialized values together,
leaving the result in third Time variable. Finally it
should display the value of this third value.
4.II Write a program to implement a binary member
function to subtract one fraction from another. The
function should simulate the subtract/assign operator
(fr1 - =fr2) and should return void.

4.III Write a program to implement a binary member


function to multiply two fractions. The function
should simulate the multiply/assign operator (fr1 *
=fr2) and should return void.

4.IV Declare and define a class for complex number. A


complex number is defined as x + y, where x defines
the real part of the number and y is the imaginary part
of the number. Write functions to implement the
operations of Add, Subtract, Multiply and Divide. Use
the following formulas:
Add: x3 = x1 + x2 y3 = y1 + y2
Subtract: x3 = x1 - x2 y3 = y1 - y2
Multiply: x3 = x1 * x2 – y1 * y2
Y3 = x1 *y2 + y1 *x2
Divide: x3 = (x1 * x2 + y1 +y2) / (x12 + y12)
y3 = (y1 * x2 - x1 *y2) / (x22 y22)
4.IV Write a program to find greatest of two numbers given
in two different classes using a friend function.

4.V Write a program to find greatest of two numbers given


in two different classes using a friend function.
4.VI Write a program to implement a binary friend function
to divide two fractions. The function should simulate
the divide/assign operator (fr1 / =fr2) and should
return void.

4.VII Create a class called Employee that contains a name


(an array of char) and an employee number (type
long). Include a member function called getData() to
get data from the user for insertion into the object, and
another function called putData() to display the data.
Assume the name has no embedded banks.
Write a main() program to exercise this class. It should
create an array of type employee, and then invite the
user to input data for up to 100 employees. Finally, it
should print out the data for the employee who has
highest salary
5.I Create a class named Stack, take private data members
according the requirements. Public methods are given
below-
(a) void push()
(b) int pop()
(c) stackfull()
(d) stackempty()
Write a main() program to exercise it.

5.II Create a class named Queue, take private data


members according to the requirements. Public
methods are given below-
(a) void insertqueue()
(b) void deletequeue()
(c) void display()

5.III Create a class named Array, take private data members


according to the requirements. Public methods are
given below-
(a) Constructor
(b) Destructor
(c) Copy constructor
(d) binarySearch()
(e) anySortingTechnique()

6.I Add an overloaded – operator for the Distance class


that subtracts two distances. It should allow statements
like dist3=dist1-dist2; . Assume the operator will
never be used to subtract a larger number from a
smaller one(that is, negative distances are not
allowed). Write a main() program to exercise it.

6.II Modify the Time class so that instead of a function


add_time() it uses the overloaded + operator to add
two times. Write a program to test this class.

6.III Overload the > operator for the Fraction class. The
operator should be a binary friend function. It should
return a Boolean value. Write a main() program to test
it.

6.IV Overload the && as the binary friend operator for the
Fraction class to determine if neither of the fraction is
zero. It should return Boolean. Write a main() program
to test it.
6.V Overload the () operator for the Fraction class to
extract the integral part of a fraction. It should return
an integer. For example, if the fraction is 18/5, it
returns 3. Write a main() program to test it.

6.VI Overload the [] operator for the Fraction class to


extract the fractional part of a fraction. It should return
a fraction. For example, if the fraction is 18/5, it
returns 3/5. Write a main() program to test it.

7.I Create a student class having data members student


name, gender, roll no., marks and age and write a
program to access the members of class using the
pointer to object members.
7.II Create a class String that uses new operator to get
memory for strings in constructor function and delete
operator in destructor function. Add member function
display( ) to display the string and upit( ) function that
converts the string to all upper case. Write some code
in main () to test this function.
7.III Define a class called Array. The class simulates a
dynamic array of integers. The class should have two
data members. The first data member is the length of
the array- i.e. the number of elements in it. The second
data member is a pointer to an array that holds the data
values. The array should have two private member
functions: one that extends the array when an element
is added and one that contracts it when an element is
deleted.
It should have the following public functions:
a) It should have one constructor that
initializes the pointer to 0.
b) It should have one logical copy constructor
that copies an array.
c) It should have one destructor that destroys
the array. The destructor must delete the
dynamic memory array.
d) It should have one function that appends
one integer at the end of the array.
e) It should have one function that chops the
array by deleting the last element.
f) It should have one function that prints the
values in the array.
All functions should return a Boolean value: true for
success and false for error.
7.IV Write a class, set, that implements a set. A set is an
unordered collection of zero or more elements with no
duplicates. The public functions are to be:
a) Constructor
b) Destructor
c) Add an element
d) List the elements
e) Intersection. An intersection of two sets is
another se that contains the common
elements from the two sets.
f) Union. A union of two sets is another set
that contains the elements in either the first
set or the second.
8.I Design three classes student, exam, result. The student
class has data members such as roll no, name. Create a
class exam having data members representing the
marks scored in six subjects. Derive the result class
from these two classes and has it own data members
such as totalmarks. Write a program to model this
relationship.
8.II Imagine a publishing company that markets both book
and audio-cassette versions of its works. Create a class
publication that stores the title(a string) and price
(type float) of a publication. From this class derive
two classes book, which adds a page count( type int);
and tape , which adds a playing time in minutes(type
float). Each of these three classes should have a
getdata( ) function to get its data from the user at the
keyboard and a putdata( ) function to display its data.
Write a main( ) program to test the book and tape
classes by creating instances of them, asking the user
to fill in their data with getdata( ) and then displaying
the data with putdata( ).
8.III Start with the publication, book, and tape classes of
the previous exercise. Add base class sales that hold
an array of three floats so that it can record the dollar
sales of a particular publication for the last three
months. Include a getdata( ) function to get three sales
amounts from the user and a putdata( ) function to
display the sales figures. Alter the tape and book
classes so they are derived from both publication and
sales. An object of class book or tape should input
and output sales data along with its other data. Write a
main( ) function to create a book object and tape
object and exercise their input output capabilities.
9.I Create a base class called shape, use this class to store
two double type values that could be used to compute
the area of that shape. Derive the specific class called
TRIANGLE and RECTANGLE from the class shape.
Add to base class, a member function get_ data ( ) to
initialize base class data members and another member
function display_area( ) to compute and display the
area of the figure. Make display_area() as a virtual
function and redefine function in the derived classes to
suit their requirements. Using these 3 classes design a
program that will accept dimension of RECTANGLE
or TRIANGLE interactivity and display the area.
9.II Create a base class Employee. The class contains
virtual functions raiseSalary() and promote().
Different types of employees like Manager, Engineer
may have their own implementations of the virtual
functions present in base class Employee. Inherit class
Manager and Engineer from the base class Employee
and demonstrate dynamic polymorphism so that
specific information of manager and engineer can be
displayed using pointer to base class.

9.III Imagine the same publishing company as described in


the exercise 4 in the previous section. Write a main( )
program that creates an array of pointers to
publication. In a loop ask the user for data about a
particular book or tape and use new to create an object
of type book or tape to hold the data. Put the pointer to
the object in the array. When the user has finished
entering the data for all books and tapes, display the
resulting data for all the books and tapes entered,
using a base class pointer that points to different
inherited objects and a single statement such as
pubarr[i]→ putdata( ); to display the data from each
object in the array .
10.I Create a template class named Array, take private data
members according to the requirements. Public
methods are given below-
(a) Constructor
(b) Destructor
(c) Copy constructor
(d) binarySearch()
(e) anySortingTechnique()

10.II Write a template class, set, that implements a set. A set


is an unordered collection of zero or more elements
with no duplicates. The public functions are to be:
g) Constructor
h) Destructor
i) Add an element
j) List the elements
k) Intersection. An intersection of two sets is
another se that contains the common
elements from the two sets.
l) Union. A union of two sets is another set
that contains the elements in either the first
set or the second.
m) Subtraction
11.I Create a class distance as described in the previous
exercise. Include member functions getdist( ) and
display to input and output the distances. Get a
number of distance values from the user and write
them to a disk file. Append them to existing values in
the file, if any. When the user signals that no more
values will be input, read the file and display all the
values.

11.II Write a program that emulates the DOS COPY


command i.e. it should copy the contents of a
character file to another file. Invoke the program with
two command-line arguments – the source file and the
destination file. In the program, check that the user has
typed the correct number of arguments and that the file
specified can be opened. The program signal an error
if the destination file already exists.

11.III Write a program that returns the size in bytes of a


program entered on the command line:
C> filesize program.ext

11.IV Write a program that reads a text file and creates


another file that is identical except that every sequence
of consecutive blank spaces is replaced by a single
space.

11.V A file contains a list of telephone numbers in the


following form:-
John 23456
Ahmed 9856
The names contain only one word and the names and
the telephone numbers are separated by white spaces.
Write a program to read the file and output the list in
two columns. The names should be left-Justified and
the numbers should be right-justified.
11.VI Write an interactive, menu-driven program that will
access the file created in the previous exercise and
implement the following tasks:-
a) Determine the telephone number of the
specified person.
b) Determine the name if a telephone
number is known.
c) Update the telephone number, whenever
there is a change.
12.I Write a program that randomly catches exceptions.
The program generates a random number with the
value of 0, 1, or 2. If the value is 0, the program does
not catch any exception. If the value is 1, the program
catches only a specified list of exceptions. If the value
is 2, the program catches all of the exceptions.
12.II Rewrite only those methods or operators in the
Fraction class that can be affected by divide by zero
error. Include code to catch the divide-by-zero error
and handle it properly. Write a main() program to
exercise it.
12.III Rewrite only those methods or operators in the Array
class that can be affected by out of index error. Include
the appropriate exception class from standard library
exception classes. Write a main program to test it.
12.IV Write a function that allocates memory for a single
data type passed as a parameter. The function uses the
new operator and returns a pointer to the allocated
memory. The function, however, catches and handles
any exceptions detected during allocation.
EXPERIMENT-1.1

1.1: A phone number, such as (212) 767-8900, can be thought of as


having three parts: the area code (212), the exchange (767), and the
number (8900). Write a program that uses a structure to store these
three parts of a phone number separately. Call the structure phone.
Create two structure variables of type phone. Inialize one, and have the
user input a number for the other one. Then display both numbers.

SOURCE CODE:
#include<iostream>

#include<iomanip>

using namespace std;

struct phone{

int area_code=212;

int exchange=767;

int number=8900;

};

int main()

struct phone my;

struct phone s;

cout<<"enter the area code,exchange and number"<<endl;

cin>>s.area_code;

cin>>s.exchange;

cin>>s.number;

cout<<"my number\t";

cout<<"("<<my.area_code<<")"<<setw(4)<<my.exchange<<"-"<<my.number<<endl;
cout<<"your number is\t";

cout<<"("<<s.area_code<<")"<<" "<<s.exchange<<"-"<<s.number<<endl;

return 0;

}
OUTPUT:
EXPERIMENT-1.2

1.2: A point on the two-dimensional plane can be represented by two


numbers: an X coordinate and Y coordinate. For example, (4,5)
represents a point 4 units to the right of the origin along the X axis, and 5
units up the Y axis. The sum of two points can be defined as a new point
whose X coordinate is the sum of the X coordinates of the two points, and
whose Y coordinate is the sum of their Y coordinates. Write a program
that uses a structure called point to model a point. Define three points,
and have the user input values to two of them. Then set the third point
equal to the sum of the other two, and display the value of the new point.

SOURCE CODE:
#include<iostream>

using namespace std;

struct point{

int x;

int y;

};

int main()

struct point p1,p2,p3;

cout<<"enter the coordinates of first point\n";

cin>>p1.x>>p1.y;

cout<<"enter the coordinates of second point\n";

cin>>p2.x>>p2.y;

p3.x=p1.x+p2.x;

p3.y=p1.y+p2.y;

cout<<"Coordinates of p1+p2 are : "<<p3.x<<" "<<p3.y;

return 0;
}
OUTPUT:
EXPERIMENT-1.3

1.3: Write a program to create a structure, Employee, having following


attributes- Private data: Employee_name, Employee_id, Employee_salary,
Employee_address Write a main program to take employee’s
information and print the same.
SOURCE CODE:
#include<iostream>

#include<iomanip>

using namespace std;

struct employee{

char name[10];

int id;

int salary;

char address[100];

};

int main()

int i,n;

struct employee s[10];

cout<<"enter the number of employes"<<endl;

cin>>n;

// cout<<"enter the details of employes"<<endl;

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

cout<<"enter detail of "<<i+1<<" employee\n";

cout<<" name\t";

cin>>s[i].name;
cout<<"id\t";

cin>>s[i].id;

cout<<"salary\t";

cin>>s[i].salary;

cout<<"address\t";

cin>>s[i].address;

cout<<"\ndetails of employes as follow\n\n\n";

cout<<"S.NO.\t"<<"name"<<setw(7)<<"id"<<setw(11)<<"salary"<<"\taddress"<<endl;

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

cout<<i+1<<"\t";

cout<<s[i].name<<"\t";

cout<<s[i].id<<"\t";

cout<<s[i].salary<<"\t";

cout<<s[i].address<<"\t";

cout<<"\n";

return 0;

}
OUTPUT:
EXPERIMENT-2.1

Write a program to create a class Employee having following attributes-

Private data:

Employee_name,Employee_id,Employee_saalry,Employee_address
Public methods:

Getinput();

Printinput();

Write a main program to test it.

SOURCE CODE:
#include<iostream>

#include<cstring>

using namespace std;

class Employee {

private:

string name,address;

int id;

int salary;

public:

Employee()

name="xyz";

id=123;

address="none";
salary=0;

void getinput()

cout<<"enter the name of Employee\n";

getline(cin,name);

cout<<"enter the address of Employee \n";

getline(cin,address);

cout<<"enter id no.\n";

cin>>id;

cout<<"enter salary of Employee\n";

cin>>salary;

void printoutput()

cout<<"name of Employee "<<name<<endl;

cout<<"id no. of "<<name<< " is "<<id<<endl;

cout<<"salary of "<<name<<" is "<<salary<<endl;

cout<<"address of "<<name<<" is "<<address<<endl;

return;

};

int main()

{
class Employee e1;

e1.getinput();

e1.printoutput();

return 0;

}
OUTPUT:
EXPERIMENT-2.2

Create a class that initiates part of functionality of the basic data type int.
Call the class Int(note different spelling). The only data in this class is an
int variable. Include member functions to initialize an Int to 0, to
initialize it to an int value, to display it( looks just like an int), and to add
two Int values. Write a program that exercises this class by creating two
initialized and one uninitialized Int values, adding these two initialized
values and placing the response in the uninitialized value, and then
displaying this result.

SOURCE CODE:

#include<iostream>

using namespace std;

class Int{

private:

int a;

public:

Int()

a=0;

void getdata()

cout<<"enter a int value"<<endl;

cin>>a;
}

Int add(Int& x)

Int d;

d.a=a+x.a;

return d;

void display()

cout<<"sum is :";

cout<<a;

};

int main()

Int i1,i2,i3;

i1.getdata();

i2.getdata();

i3=i1.add(i2);

i3.display();

}
OUTPUT:
EXPERIMENT-2.3

Define a class to represent a bank account. Include the following


members:
Data Members: Name of the depositor, Account no. , Type of account, Balance amount.
Member Functions: To assign initial values,
To deposit an amount,
To withdraw an amount after checking the balance,
To display name and balance.
Write a main program to test the program.

#include<iostream>

#include<cstring>

using namespace std;

class Account{

private:

string name,type;

int accountno;

int balance;

public:

Account()

name="xyz";

accountno=123;

type="none";

balance=0;

void getinput()

cout<<"enter the name of account holder\n";


getline(cin,name);

cout<<"enter the type \n";

getline(cin,type);

cout<<"enter account no.\n";

cin>>accountno;

cout<<"enter balance\n";

cin>>balance;

void deposit(int d)

balance=balance+d;

cout<<"you deposited "<<d<<" "<<endl<<"your current balance is "<<balance<<endl;

return;

void withdraw(int w)

if(w>balance)

cout<<"transaction decline\nerror code:xzx123";

return;

if(w<0)

cout<<"invalid input"<<endl;

return;
}

balance=balance-w;

cout<<"you withraw "<<w<<"\n"<<"your current balance is "<<balance;

void display()

cout<<"name = "<<name<<endl;

cout<<"account = "<<accountno<<endl;

cout<<"type = "<<type<<endl;

cout<<"balance = "<<balance<<endl;

return;

};

int main()

char ch;

int c,d,w;

class Account a1;

a1.getinput();

while(ch!='n')

cout<<"select from these\n1.deposit\n2.withdraw\n3.display\n";


cin>>c;

switch(c)

case 1:

cout<<"enter the amount you want to deposit\n";

cin>>d;

a1.deposit(d);

break;

case 2:cout<<"enter the amount you want to withdraw\n";

cin>>w;

a1.withdraw(w);

break;

case 3:

a1.display();

break;

cout<<"you want more transaction"<<endl;

cin>>ch;

return 0;

}
OUTPUT:
EXPERIMENT NO:2.4

Imagine a tollbooth at a bridge. Cars passing by the booth are expected


to pay a fifty-cent toll. Mostly they do, but sometimes a car goes by
without paying. The tollbooth keeps track of the number of cars that
have gone by, and of the total amount of money collected.Model this
tollbooth with a class called TollBooth. The two data items are a type
unsigned int to hold the total number of cars, and a type double to hold
the total number of cars, and a type double to hold the total amount of
money collected. An initialization function sets both these values to 0. A
member function called payingCar() increments the car total and adds
0.50 to the cash total. Another function, called nopayCar(), increments
the car total but adds nothing to the cash total. Finally, a member
function called display() desplays the two totals.

Include a program to test this class. This program shold allow the user to
push one key to count a paying car, and another to count a nonpaying
car.
#include<iostream>

using namespace std;

class tollbooth{

int count;

float amount;

public:

tollbooth()
{

count=0;

amount=0.0;

void payingCar()

amount+=.5;

count++;

return;

void nonpayCar()

count++;

return;

void display()

cout<< "Total Cars Passed: " <<count<< endl ;

cout<< "Total Balance: " << amount;

return;

};

int main()

tollbooth toll;
char ch;

while(ch!='n')

cout << endl << "1. Payed Toll"

<< endl << "2. Passed without Toll"

<< endl << "Enter Option: ";

int opt;

cin >> opt;

cout << endl;

if(opt==1)

toll.payingCar();

if(opt==2){

toll.nonpayCar();

cout<<"more car come?"<<endl;

cin>>ch;

toll.display();

return 0;

}
OUTPUT:
EXPERIMENT-3.1

Create a class called Employee that contains a name (an array of char)
and an employee number (type long). Include a member function called
getData() to get data from the user for insertion into the object, and
another function called putData() to display the data. Assume the name
has no embedded banks.

Write a main() program to exercise this class. It should create an array


of type employee, and then invite the user to input data for up to 100
employees. Finally, it should print out the data for all the employees.

SOURCE CODE:
#include<iostream>

#include<string>

using namespace std;

class Employee{

private:

string name;

int id;

public:

Employee()

name=" ";

id=0;

void getData()
{

cout<<"enter the name \n";

cin>>name;

cout<<"enter the id \n";

cin>>id;

return;

void putdata()

cout<<"name \t"<<name<<"\tID:\t"<<id<<endl;

return;

};

int main()

const int max=100;

Employee a[max];

int i;

for(i=0;i<2/*max*/;i++)

cout<<"enter detail of "<<i+1<<" Employee\n";

a[i].getData();

cout << "The Details of the Employees are:" << endl;

for (i = 0;i<2/*max*/;i++)
{

a[i].putdata();

return 0;}

OUTPUT:
EXPERIMENT-3.2

Create the database of students using Class, having the following


attributes :

roll_no, student_name, student_address, student_city, student_pin,


student_sem, rank, and

branch. Also write the program to enter the data for 500 students in any
order and then display the list of students for a given branch and
semester on display.
SOURCE CODE:
#include<iostream>

#include<string>

using namespace std;

class Student

private:

string Name, Address, City, Branch;

long int Roll, Pin;


public:

Student()

Name ="", Address ="", City ="", Branch = "";

Roll =0, Pin = 0;

void Input()

cout << "Enter Name: ";

cin >> Name;

cout << "Address: ";

cin >> Address;

cout << "City: ";

cin >> City;

cout << "Branch: ";

cin >> Branch;

cout << "Roll No: ";

cin >> Roll;

cout << "Pin: ";

cin >> Pin;

return;

void Display()

cout << "Name: " << Name << "\tAddress: " << Address

<< endl << "City: " << City << "\tBranch: " << Branch

<< endl << "Roll No.: " << Roll << "\tPin: " << Pin
<< endl;

return;

};

int main()

const int max= 500;

Student student[max];

int i;

for (i=0;i<1;i++)

cout << "\nEnter Details for Student " << i + 1 << endl;

student[i].Input();

for (i=0; i<1;i++)

cout << "\nDetails for Student " <<i+1<< endl;

student[i].Display();

return 0;

}
OUTPUT:
EXPERIMENT-3.3

Write a program that calculates the average of up to 100 English


distances input by the user. Create an array of objects of the Distance
class. To calculate the average, you can create dist_add() method, that
perform addition over 100 distance’s object. You will also need a
member function that divides a Distance value by an integer.
SOURCE CODE:
#include<iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
void showDist();
Distance()
{
feet=0;
inches=0;
}
void add(Distance& d)
{
feet=d.feet+feet;
inches=d.inches+inches;
if(inches>=12)
{
while(inches<12)
{
inches-=12;
feet++;
}
}
return;
}
void getDist()
{
cout<<"enter number of feet"<<endl;
cin>>feet;
cout<<"enter number of inches"<<endl;
cin>>inches;
}
};

void Distance::showDist()
{
cout<<"feet = "<<feet<<endl<<"inches = "<<inches<<endl;
}
int main()
{
int n,i,avg;
Distance d[100],dis1,dis2;
cout<<"enter number of distance you want of enter"<<endl;
cin>>n;
for(i=0;i<n;i++)
d[i].getDist();
for(i=0;i<n;i++)
{

dis1.add(d[i]);
}
for(i=0;i<n;i++)
d[i].showDist();
dis1.showDist();
return 0;
}
OUTPUT:
EXPERIMENT NO:4.1

Create a class called Time that has separate int member data for hours,
minutes, and seconds. One constructor should initialize this data to 0,
and another should initialize it to fixed values. A member function
should add two objects of type time passed as arguments. A main()
program should create two initialized time objects, and one that isn’t
initialized. The it should add the two initialized values together, leaving
the result in third Time variable. Finally it should display the value of
this third value.

SOURCE CODE:
#include<iostream>
using namespace std;
class time{
private:
int hour,minute,second;
public:
time()
{
hour=0;
minute=0;
second=0;
}
time(int x,int y,int z)
{
hour=x;
minute=y;
second=z;
}
void getdata()
{
cout<<"enter the number of hours"<<endl;
cin>>hour;
cout<<"enter number of minutes"<<endl;
cin>>minute;
cout<<"enter the number of seconds"<<endl;
cin>>second;
}
time addtwo(time& t)
{
time t1;
t1.second=this->second +t.second;
t1.minute=this->minute+t.minute;
t1.hour=this->hour+t.hour;
while(t1.second>59)
{
t1.second-=60;
t1.minute+=1;
}
while(t1.minute>59)
{
t1.minute-=60;
t1.hour+=1;
}
return t1;
}
void display()
{

cout<<"hours :"<<hour<<"\nminute :"<<minute<<"\nseconds :"<<second<<endl;


return;
}
};
int main()
{
int h,m,s;

time t2(0,0,0),t3(0,0,0),t4;
t2.getdata();
t3.getdata();
t4=t2.addtwo(t3);
t4.display();
return 0;
}
OUTPUT:
EXPERIMENT NO:4.2

Write a program to implement a binary member function to subtract one


fraction from another. The function should simulate the subtract/assign
operator (fr1 - =fr2) and should return void.

SOURCE CODE:

#include <iostream>
using namespace std;
class Fraction
{
intnum;
intdenom;
public:
void print();
Fraction(int,int);
void show();
void operator-=(Fraction&);
};
Fraction::Fraction(intn,int d)
{
num=n;
denom=d;
}
void Fraction::print()
{
cout<<"result="<<num<<"/"<<denom<<endl;
}
void Fraction:: show()
{
cout<<"fraction:"<<num<<"/"<<denom<<endl;
}
void Fraction:: operator-=(Fraction& f)
{
num=f.num*denom-num*f.denom;
denom=f.denom*denom;
}
int main()
{
Fraction f1(3,4);
Fraction f2(4,5);
f1.show();
f2.show();
f1-=f2;
f1.print();
return 0;
}
OUTPUT:
EXPERIMENT NO:4.3

Write a program to implement a binary member function to multiply


two fractions. The function should simulate the multiply/assign
operator (fr1 * =fr2) and should return void.

SOURCE CODE:
#include<iostream>
using namespace std;
class Fraction{
private:
int num;
int denom;
public:
Fraction(int x=1,int y=1)
{
num=x;
denom=y;
}
Fraction(Fraction& f)
{
num=f.num;
denom=f.denom;
}
void operator*=(Fraction& f2)
{
(*this).num=(*this).num*f2.num;
(*this).denom=(*this).denom*f2.denom;
cout<<"after product"<<endl;
cout<<num<<"/"<<denom;
return;
}
void getdata()
{
cout<<"enter the numerator"<<endl;
cin>>num;
cout<<"enter the denominator"<<endl;
cin>>denom;
}
void display()
{
cout<<num<<"/"<<denom<<endl;
}
};
int main()
{
Fraction F1,F2,F3;
F1.getdata();
F2.getdata();
F2.display();
F1.display();
cout<<"after product"<<endl;
F1*=F2;
return 0;
}
OUTPUT:
EXPERIMENT NO:4.4

Declare and define a class for complex number. A complex number is


defined as x + y, whre x defines the real part of the number and y is the
imaginary part of the number. Write functions to implement the
operations of Add, Subtract, Multiply and Divide. Use the following
formulas:
Add : x3 = x1 + x2 y3 = y1 + y2
Subtract : x3 = x1 – x2 y3 = y1 – y2
Multiply : x3 = x1 * x2 – y1 * y2
Y3 = x1 *y2 + y1 *x2
Divide : x3 = (x1 * x2 + y1 +y2) / (x12 + y12)
y3 = (y1 * x2 – x1 *y2) / (x22 + y22)

SOURCE CODE :
#include<iostream>
using namespace std;
class Complex
{
float real, imag;
public:
Complex(float Real = 0, float Imag = 0)
{
real = Real;
imag = Imag;
}

Complex operator +(Complex c1)


{
Complex c;
c.real = real + c1.real;
c.imag = imag + c1.imag;
return c;
}
Complex operator -(Complex c1)
{
Complex c;
c.real = real - c1.real;
c.imag = imag - c1.imag;
return c;
}
Complex operator *(Complex c1)
{
Complex c;
c.real = real *c1.real - imag*c1.imag;
c.imag = imag*c1.real + real*c1.imag;
return c;
}
Complex operator /(Complex c1)
{
Complex c;
c.real = real *c1.real + imag*c1.imag;
c.imag = imag*c1.real - real*c1.imag;
int x = c1.real*c1.real + c1.imag*c1.imag;
c.real /= x;
c.imag /= x;
return c;
}
void Print()
{
if(imag>=0)
cout << real << "+" << imag << "i";
else cout << real << imag << "i";
}
void getdata()
{
cout<<"enter the real part"<<endl;
cin>>real;
cout<<"enter the imaginary part"<<endl;
cin>>imag;
}
};
int main()
{
Complex c1,c2;
c1.getdata();
c2.getdata();
cout << "Complex Nums are: ";
c1.Print();
cout << "\t";
c2.Print();

cout << "\nSum: ";


(c1 + c2).Print();

cout << "\nDifference: ";


(c1 - c2).Print();

cout << "\nProduct: ";


(c1 * c2).Print();

cout << "\nDivision: ";


(c1 / c2).Print();

return 0;
}
}
OUTPUT:
EXPERIMENT NO:4.5

Write a program to find greatest of two numbers given in two different


classes using a friend function.

SOURCE CODE:
#include<iostream>
using namespace std;
class xyz;
class abc{
int a;
public:
abc(int i)
{
a=i;
}
friend int max(xyz& m,abc& n);
};
class xyz{
int y;
public:
xyz(int i)
{
y=i;
}
friend int max(xyz& m,abc& n);
};
int max(xyz& m,abc& n)
{
if(m.y>n.a)
{
cout<<m.y;
return 0;
}
else
{
cout<<n.a;
return 0;
}
}
int main(){
int m,n;
cout<<"enter value for first function"<<endl;
cin>>n;
cout<<"enter value for second function"<<endl;
cin>>m;
abc ABC(n);
xyz XYZ(m);
cout<<"maximum value is"<<endl;
max(XYZ,ABC);
return 0;
}
OUTPUT:
EXPERIMENT NO:4.6

Write a program to implement a binary member function to subtract one


fraction from another. The function should simulate the subtract/assign
operator (fr1 - =fr2) and should return void.

SOURCE CODE:

class Fraction
{
int num, denom;
public:
Fraction(int Num = 1, int Denom = 1)
{
num = Num;
denom = Denom;
}
void Subtract(Fraction f)
{
num = num*f.denom - f.num*denom;
denom *= f.denom;
}
void operator -=(Fraction f)
{
num = num*f.denom - f.num*denom;
denom *= f.denom;
}
Fraction operator -(Fraction f)
{
Fraction t;
t.num = num*f.denom - f.num*denom;
t.denom *= f.denom;
return t;
}
void Multiply(Fraction f)
{
num *= f.num;
denom *= f.denom;
}

void operator *=(Fraction f)


{
num *= f.num;
denom *= f.denom;
}

Fraction operator *(Fraction f)


{
Fraction t;
t.num = num * f.num;
t.denom = denom * f.denom;
return t;
}
void operator /=(Fraction f)
{
num *= f.denom;
denom *= f.num;
}
void Print()
{
cout << num << "/" << denom;
}
};
int main()
{
Fraction f1(3, 4), f2(5, 3), f3;
cout << "Fraction 1 is: ";
f1.Print();
cout << "\nFraction 2 is: ";
f2.Print();

f3 = f1;
f3.Subtract(f2);
cout << "\nTheir Difference is: ";
f3.Print();

f3 = f1;
f3.Multiply(f2);
cout << "\nTheir Product is: ";
f3.Print();

getch();
return 0;
}
OUTPUT:
EXPERIMENT NO:4.7

Create a class called Employee that contains a name (an array of char)
and an employee number (type long). Include a member function called
getData() to get data from the user for insertion into the object, and
another function called putData() to display the data. Assume the name
has no embedded banks.

Write a main() program to exercise this class. It should create an array


of type employee, and then invite the user to input data for up to 100
employees. Finally, it should print out the data for all the employees.

SOURCE CODE:
#include<iostream>
using namespace std;
class employee{
private:
string name;
double number;
public:
employee()
{
name="xyz";
number=0;
}
void getdata()
{
cout<<"enter the name\n"<<endl;
cin>>name;
cout<<"enter the employee number"<<endl;
cin>>number;
}
void putdata()
{
cout<<"name :"<<name;
cout<<"\t number :"<<number<<endl;
}
};
int main()
{
int n,i;
employee e[100];
cout<<"enter the number of employee\n";
cin>>n;
for(i=0;i<n;i++)
{
e[i].getdata();
}
for(i=0;i<n;i++)
{
e[i].putdata();
}
return 0;
}
OUTPUT:
EXPERIMENT NO:5.1

Create a class named Stack, take private data members according the
requirements. Public methods are given below-

void push()
(e)int pop()
(f) stackfull()
(g) stackempty()
Write a main() program to exercise it.

SOURCE CODE:
#include<iostream>
using namespace std;
class Stack
{
int a[5],item;
public:
int top;
void push();
int pop();
intstackfull();
intstackempty();
void display();
};
int Stack::stackfull()
{
if(top==4)
{
return 0;}
else return 1;
}
int Stack::stackempty()
{
if(top==-1)
{
return 0;
}
else return 1;
}
void Stack::push()
{

cout<<"enter the no. u want to enter"<<endl;


cin>>item;
top=top+1;
a[top]=item;
}
int Stack::pop()
{ item=a[top];
top=top-1;
}
void Stack::display()
{
inti;
cout<<"stack is"<<endl<<endl;
for(i=0;i<=top;i++)
{
cout<<a[i]<<endl;
}
}
int main()
{
Stack s;
s.top=-1;
s.stackempty();
s.stackfull();
int choice;
int option = 1;
s.top = -1;
while (option)
{cout<<"1.push"<<endl<<"2.pop"<<endl<<"3.display"<<endl;
cout<<"Enter your choice\n";
cin>>choice;
switch (choice)
{
case 1: s.push();
break;
case 2: s.pop();
break;
case 3: s.display();
break;}
}
}
OUTPUT:
EXPERIMENT NO. 5.2

Create a class named Queue, take private data members according to the
requirements. Public methods are given below-
(d) void insertqueue()
(e)void deletequeue()
(f) void display()
Write a main() program to exercise it.

Sol. #include<iostream>
#include<cstdlib>
using namespace std;
class Queue
{
int Front;
int rear;
int data[100];
public:
intmaxn;
Queue(){Front=-1;rear=-1;}
voidinsertqueue();
voiddeletequeue();
void display();
};
void Queue::insertqueue()
{
if(Front==-1 && rear==-1)
{
Front=0;rear=0;
cout<<"enter item ";
cin>>data[rear];
}
else if(rear<(maxn-1))
{
rear=rear+1;
cout<<"enter data ";
cin>>data[rear];
}
else if(rear>(maxn-2))
{
cout<<"no more space "<<endl;
} }
void Queue::deletequeue()
{
if(Front==-1&&rear==-1)
cout<<"empty list ";
else if(Front<rear)
{
cout<<"deleted item is: "<<data[Front]<<endl;
Front=Front+1;
}
}
void Queue::display()
{
inti;
cout<<"queue is: "<<endl;
for(i=Front;i<=rear;i++)
{
cout<<data[i]<<" ";
}
}
int main()
{
intn,m,ch;
Queue s;
cout<<"number of data items u want in your queue";
cin>>s.maxn;

cout<<"enter 1 for insert"<<endl<<"enter 2 for delete"<<endl<<"enter 3 for display"<<endl<<"enter


4 for exit"<<endl;
while(1){ cout<<"enter your choice ";
cin>>ch;

switch(ch)
{
case 1:
s.insertqueue();
break;
case 2:
s.deletequeue();
break;
case 3:
s.display();
break;
case 4:
exit(100);
}
}
return 0;
}
OUTPUT:
EXPERIMENT NO. 5.3

Create a class named Array, take private data members according to the
requirements. Public methods are given below-
(f) Constructor
(g) Destructor
(h) Copy constructor
(i) binarySearch()
(j) anySortingTechnique()

SOURCE CODE :

#include<iostream>
#define SWAP(x, y, t) {t = x; x = y; y = t;}
using namespace std;
class Array
{ int *a;
intlen;
public:
Array(int l = 0);
~Array() {
delete []a;}
Array(Array &b);
void display();
intbinarySearch(int item);
voidselectionSort();
};
Array::Array(int l)
{ len = l;
a = new int[len + 1];
for(inti = 0; i<len; i++)
{
cin>>a[i];
}
}
Array::Array(Array &b)
{ len = b.len;
a = new int[len + 1];
for(inti = 0; i<len; i++)
{
a[i] = b.a[i];
}
}
int Array::binarySearch(int item)
{
int left, mid, right;
left = 0;
right = len - 1;
while(left < right)
{
mid = (left + right) / 2;
if(a[mid] == item)
{
return mid;
}
else if(a[mid] < item)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
void Array::selectionSort()
{
inti, j, pos, tmp;
for(i = 0; i<len - 1; i++)
{
pos = i;
for(j = i + i; j <len; j++)
{
if(a[pos] > a[j])
{
pos = j;
}
}
if(pos != i)
{
SWAP(a[pos], a[i], tmp);
}
}
}
void Array::display()
{
for(inti = 0; i<len; i++)
{
cout<<a[i]<<"\t";
}
return;
}

intmain()
{
int l, x;
cout<<"\nEnter the number of elements in the Array : ";
cin>>l;
Array arr(l);
cout<<"\nCopying this into another Array...\n";
Array brr(arr);
while(1)
{
cout<<"\n1. Sort 2. Search\n3. Display\n4. Exit\n";
cin>>l;
switch(l)
{
case 1: brr.selectionSort();
break;

case 2: cout<<"\nEnter the element to be searched for : ";


cin>>x;
x = brr.binarySearch(x);
if(x != -1)
{
cout<<"\nElement is present at index "<<x<<endl;
}
else
{
cout<<"\nElement not present in the Array.\n";
}
break;
case 3: brr.display();
break;
case 4: return 0;
default:cout<<"\nWrong choice entered.\n";
}
}
return 0;
}
OUTPUT:
EXPERIMENT NO.6.1

Add an overloaded – operator for the Distance class that subtracts two
distances. It should allow statements like dist3=dist1-dist2; . Assume the
operator will never be used to subtract a larger number from a smaller
one(that is, negative distances are not allowed). Write a main() program
to exercise it.

SOURCE CODE:
#include<iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
/*Distance(int x,float y)
{
feet=x;
inches=y;
} */
void getDist();
void showDist();
Distance operator-(Distance& f)
{
Distance temp;
if(inches<f.inches)
{
feet--;
inches+=12;
}
temp.feet=feet-f.feet;
temp.inches=inches-f.inches;
return temp;
}
};
void Distance::getDist()
{cout<<"enter number of feet"<<endl;
cin>>feet;
cout<<"enter number of inches"<<endl;
cin>>inches;
}
void Distance::showDist()
{
cout<<"feet = "<<feet<<endl<<"inches = "<<inches<<endl;
}
int main()
{
Distance d1,d2,d3;
d1.getDist();
d2.getDist();
d3=d1-d2;
d3.showDist();
return 0;
}
OUTPUT:
EXPERIMENT NO.6.2

Modify the Time class so that instead of a function add_time() it uses the
overloaded + operator to add two times. Write a program to test this
class.

SOURCE CODE:
#include<iostream>
using namespace std;
class time{
private:
int hour,minute,second;
public:
time()
{
hour=0;
minute=0;
second=0;
}
time(int x,int y,int z)
{
hour=x;
minute=y;
second=z;
}
time operator+(time& t)
{
time t1;
t1.second=this->second +t.second;
t1.minute=this->minute+t.minute;
t1.hour=this->hour+t.hour;
while(t1.second>59)
{
t1.second-=60;
t1.minute+=1;
}
while(t1.minute>59)
{
t1.minute-=60;
t1.hour+=1;
}
return t1;
}
void display()
{

cout<<"hours :"<<hour<<"\nminute :"<<minute<<"\nseconds :"<<second<<endl;


return;
}
void gettime()
{
cout<<"enter number of hours\n";
cin>>hour;
cout<<"enter number of minutes\n";
cin>>minute;
cout<<"enter number of second\n";
cin>>second;
}
};
int main()
{
time t2,t3,t4;
t2.gettime();
t3.gettime();
t4=t2+t3;
t4.display();
return 0;
}
OUTPUT:
EXPERIMENT NO.6.3

Overload the > operator for the Fraction class. The operator should be a
binary friend function. It should return a Boolean value. Write a main()
program to test it.

SOURCE CODE:
#include<iostream>

using namespace std;

class Fraction{

private:

int num;

int denom;

public:

Fraction(int x=1,int y=1)

num=x;

denom=y;

Fraction(Fraction& f)

num=f.num;

denom=f.denom;

bool operator>(Fraction& f2)

if(((num*f2.denom)-(f2.num*denom))>0)
{

return true;

else

return false;

void getdata()

cout<<"enter the numerator"<<endl;

cin>>num;

cout<<"enter the denominator"<<endl;

cin>>denom;

void display()

cout<<num<<"/"<<denom<<endl;

};

int main()

int i;

Fraction F1,F2,F3;

F1.getdata();

F2.getdata();

F2.display();
F1.display();

i=F1>F2;

cout<<i;

return 0;

}
OUTPUT:
EXPERIMENT NO:6.4

Overload the && as the binary friend operator for the Fraction class to
determine if neither of the fraction is zero. It should return Boolean.
Write a main() program to test it.

SOURCE CODE:
#include<iostream>

using namespace std;

class Fraction{

private:

int num;

int denom;

public:

Fraction(int x=1,int y=1)

num=x;

denom=y;

Fraction(Fraction& f)

num=f.num;

denom=f.denom;

bool operator&&(Fraction& f2)

if(num!=0&&f2.num!=0)
{

return true;

else

return false;

void getdata()

cout<<"enter the numerator"<<endl;

cin>>num;

cout<<"enter the denominator"<<endl;

cin>>denom;

void display()

cout<<num<<"/"<<denom<<endl;

};

int main()

int i;

Fraction F1(3,5),F2(4,5),F3;

F1.getdata();

F2.getdata();

F2.display();
F1.display();

i=F1&&F2;

cout<<i;

return 0;

}
OUTPUT:
EXPERIMENT NO. 6.5

Overload the () operator for the Fraction class to extract the integral
part of a fraction. It should return an integer. For example, if the fraction
is 18/5, it returns 3. Write a main() program to test it.

SOURCE CODE:
#include<iostream>

using namespace std;

class fraction

private:

int num;

int denom;

public:

void getDist();

void showDist();

int operator()(fraction &)

int a,n;

a=(num/denom);

cout<<a<<endl;

return 0;

};

void fraction::getDist()
{cout<<"enter number of num"<<endl;

cin>>num;

cout<<"enter number of denom"<<endl;

cin>>denom;

void fraction::showDist()

cout<<num<<"/"<<denom;

int main()

fraction d1,d2,d3;

d1.getDist();

cout<<"integeral part is :";

d1(d2);

return 0;

}
OUTPUT:
EXPERIMENT NO. 6.6

Overload the [] operator for the Fraction class to extract the fractional
part of a fraction. It should return a fraction. For example, if the fraction
is 18/5, it returns 3/5. Write a main() program to test it.

SOURCE CODE:

#include<iostream>

using namespace std;

class fraction

private:

int num;

int denom;

public:

void getDist();

void showDist();

int operator[](fraction &)

int a,n;

a=(num/denom);

n=num-a*denom;

cout<<n<<"/"<<denom;

return 0;
}

};

void fraction::getDist()

{cout<<"enter number of num"<<endl;

cin>>num;

cout<<"enter number of denom"<<endl;

cin>>denom;

void fraction::showDist()

cout<<num<<"/"<<denom;

int main()

fraction d1,d2,d3;

d1.getDist();

cout<<"fraction part is :";

d1[d2];

return 0;

}
OUTPUT:
EXPERIMENT NO: 7.1

Create a student class having data members student name, gender, roll
no., marks and age and write a program to access the members of class
using the pointer to object members.
#include<iostream>
using namespace std;
class student{
private:
string name,gender;
int roll,age;
float mark;
public:
void getdata()
{
cout<<"enter the name of student"<<endl;
cin>>name;
cout<<"enter gender"<<endl;
cin>>gender;
cout<<"enter roll no. ,marks and age"<<endl;
cin>>roll;
cin>>mark;
cin>>age;
}
void display()
{
cout<<"name :"<<name<<endl;
cout<<"gender :"<<gender<<endl;
cout<<"roll no. :"<<roll<<endl;
cout<<"age :"<<age<<endl;
cout<<"marks :"<<mark<<endl;
}
};
int main()
{
class student obj;
class student *ptr;
ptr=&obj;
ptr->getdata();
ptr->display();
return 0;
}
OUTPUT:
EXPERIMENT NO:7.2

Create a class String that uses new operator to get memory for strings in
constructor function and delete operator in destructor function. Add
member function display( ) to display the string and upit( ) function that
converts the string to all upper case. Write some code in main () to test
this function.
#include<iostream>

#include<string.h>

using namespace std;

class String{

private:

char *name;

int length;

public:

String()

length=0;

name= new char[length+1];

String(char *s)

length=strlen(s);

name=new char[length+1];

strcpy(name,s);

void upit()
{

int i;

for(i=0;i<length;i++)

name[i]=name[i]+'A'-'a';

void display()

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

};

int main()

char name[100];

cout<<"enter the name"<<endl;

cin>>name;

class String s(name);

s.display();

s.upit();

s.display();

return 0;

}
OUTPUT:
EXPERIMENT NO:7.3

Define a class called Array. The class simulates a dynamic array of


integers. The class should have two data members. The first data
member is the length of the array- i.e. the number of elements in it. The
second data member is a pointer to an array that holds the data values.
The array should have two private member functions: one that extends
the array when an element is added and one that contracts it when an
element is deleted.

It should have the following public functions:

It should have one constructor that initializes the pointer to 0.

It should have one logical copy constructor that copies an array.

It should have one destructor that destroys the array. The destructor
must delete the dynamic memory array.

It should have one function that appends one integer at the end of the
array.

It should have one function that chops the array by deleting the last
element.

It should have one function that prints the values in the array.

All functions should return a Boolean value: true for success and false
for error.
#include<iostream>
using namespace std;
class Array
{
private:
int l;
int* arr;
int i;
void extend()
{
int* arr2;
if(i==0)
{
arr=new int;
i++;
}
else
{
arr2=new int[++i];
for(int j=0;j<=i-2;j++)
{
arr2[j]=arr[j];
}
delete(arr);
arr=arr2;
}
}
void contract()
{
int* arr2;
arr2=new int[--i];
for(int j=0;j<i;j++)
{
arr2[j]=arr[j];
}
delete(arr);
arr=arr2;
}
public:
Array(int x)
{
arr=NULL;
l=x;
i=0;
}
Array(Array& a)
{
l=a.l;
arr=a.arr;
}
~Array()
{
delete(arr);
}
bool append(int x)
{
if(i!=l)
{
extend();
arr[i-1]=x;
return 1;
}
else
return 0;
}
bool chop()
{
if(i!=0)
{
contract();
return 1;
}
else
{
return 0;
}
}
void show()
{
for(int j=0; j<i; j++)
{
cout<<arr[j]<<endl;
}
}
};
int main()
{
int i,a,j;
Array x(5);
while(j)
{
cout<<"select from the following"<<endl<<"1.append"<<endl<<"2.chop"<<endl;
cin>>i;

if(i==1)
{
cout<<"enter the value\n";
cin>>a;
x.append(a);
}
if(i==2)
x.chop();
cout<<"want more operation?(0/1)\n";
cin>>j;
}

x.show();
}
OUTPUT:
EXPERIMENT NO:7.4

Write a class, set, that implements a set. A set is an unordered collection


of zero or more elements with no duplicates. The public functions are to
be:

List the elements

Constructor

Destructor

Add an element

Intersection. An intersection of two sets is another se that contains the


common elements from the two sets.

Union. A union of two sets is another set that contains the elements in
either the first set or the second.

#include<iostream>

#include<string.h>

#include<conio.h>
using namespace std;

class Employee

protected:

double Salary;

char Post[20];

public:

virtual void raiseSalary() = 0;

virtual void promote() = 0;

virtual void display() = 0;

};

class Manager :public Employee

public:

Manager():Employee()

strcpy(Post,"Manager");

void raiseSalary()

cout << "Enter Salary for Manager: ";

cin >> Salary;

}
void promote()

strcpy(Post, "Head Manager");

void display()

cout << "Manager Detail\tSalary: " << Salary << "\tPost: " << Post << endl;

};

class Engineer :public Employee

public:

Engineer():Employee()

strcpy(Post, "Engineer");

void raiseSalary()

cout << "Enter Salary for Engineer: ";

cin >> Salary;

void promote()

strcpy(Post, "Senior Engineer");


}

void display()

cout << "Engineer Detail\tSalary: " << Salary << "\tPost: " << Post << endl;

};

int main()

Manager manager;

manager.raiseSalary();

Engineer engineer;

engineer.raiseSalary();

engineer.display();

manager.display();

cout << "\nPromoting Manager and Engineer!\n";

engineer.promote();

manager.promote();

engineer.display();

manager.display();

getch();

return 0;

}
OUTPUT:
EXPERIMENT NO.8.1

Design three classes student, exam, result. The student class has data
members such as roll no, name. Create a class exam having data
members representing the marks scored in six subjects. Derive the
result class from these two classes and has it own data members such as
totalmarks. Write a program to model this relationship.
#include<iostream>
#include<string>
using namespace std;
class Student
{
protected:
string name;
long long int roll;
public:
Student()
{

name='\0';
roll=0;
}
void getdata1()
{
cout<<"enter the name and roll no."<<endl;
cin>>name;

cin>>roll;
}
};
class Exam
{
protected:
int de;
int oops;
int ob;
int webd, ds;
int pdfs;
public:
void getdata3()
{ cout<<"enter your marks in 6 sub";
cin>>de>>oops>>ob>>webd>>ds>>pdfs;
}
};
class marks:public Student,public Exam
{
private:
int totalmarks;
public:
void totalmark()
{
totalmarks=de+oops+ob+webd+ds+pdfs;
}
void getdata2()
{
getdata1();
getdata3();
}
void show()
{totalmark();
cout<<name<<endl;
cout<<roll<<endl;
cout<<totalmarks<<endl;
}
};
int main()
{
marks m;
m.getdata2();
m.show();

}
OUTPUT:
EXPERIMENT NO:8.2

Imagine a publishing company that markets both book and audio-


cassette versions of its works. Create a class publication that stores the
title(a string) and price (type float) of a publication. From this class
derive two classes book, which adds a page count( type int); and tape ,
which adds a playing time in minutes(type float). Each of these three
classes should have a getdata( ) function to get its data from the user at
the keyboard and a putdata( ) function to display its data.

Write a main( ) program to test the book and tape classes by creating
instances of them, asking the user to fill in their data with getdata( ) and
then displaying the data with
putdata( ).
#include<iostream>
#include<string>
using namespace std;
class publication
{
protected:
string title;
float price;
public:
void getdata()
{
cin>>title>>price;
}
void putdata()
{
cout<<title<<price<<endl;
}
};
class sales
{
protected:
float arr[3];
public:
void getdata()
{
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
for(int i=0;i<3;i++)
cout<<arr[i]<<" "<<endl;
}
};
class book:public publication,public sales
{
private:
int pagecount;
public:
void getdata()
{
cin>>title>>price>>pagecount;
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
cout<<title<<" "<<price<<" "<<pagecount<<endl;
for(int i=0;i<3;i++)
cout<<arr[i]<<endl;
}
};
class tape:public publication,public sales
{
private:
int playingtime;
public:
void getdata()
{
cin>>title>>price>>playingtime;
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
cout<<title<<" "<<price<<" "<<playingtime<<endl;
for(int i=0;i<3;i++)
cout<<arr[i]<<endl;
}
};
int main()
{
book b1;
tape t1;
b1.getdata();
b1.putdata();
t1.getdata();
t1.putdata();
}
OUTPUT:
EXPERIMENT NO:8.3

Start with the publication, book, and tape classes of the previous
exercise. Add base class sales that hold an array of three floats so that it
can record the dollar sales of a particular publication for the last three
months. Include a getdata( ) function to get three sales amounts from the
user and a putdata( ) function to display the sales figures. Alter the tape
and book classes so they are derived from both publication and sales. An
object of class book or tape should input and output sales data along
with its other data. Write a main( ) function to create a book object and
tape object and exercise their input output capabilities.
#include<iostream>
#include<string>
using namespace std;
class publication
{
protected:
string title;
float price;
public:
void getdata()
{
cin>>title>>price;
}
void putdata()
{
cout<<title<<price<<endl;
}
};
class sales
{
protected:
float arr[3];
public:
void getdata()
{
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
for(int i=0;i<3;i++)
cout<<arr[i]<<" "<<endl;
}
};
class book:public publication,public sales
{
private:
int pagecount;
public:
void getdata()
{
cin>>title>>price>>pagecount;
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
cout<<title<<" "<<price<<" "<<pagecount<<endl;
for(int i=0;i<3;i++)
cout<<arr[i]<<endl;
}
};
class tape:public publication,public sales
{
private:
int playingtime;
public:
void getdata()
{
cin>>title>>price>>playingtime;
for(int i=0;i<3;i++)
cin>>arr[i];
}
void putdata()
{
cout<<title<<" "<<price<<" "<<playingtime<<endl;
for(int i=0;i<3;i++)
cout<<arr[i]<<endl;
}
};
int main()
{
book b1;
tape t1;
b1.getdata();
b1.putdata();
t1.getdata();
t1.putdata();
}
8.4: Class B is inherited from A. a uses a dynamic pointer. B inherits that
dynamic pointer and uses another dynamic pointer. Write a constructor
and destructor for both A and B.
#include<iostream>
using namespace std;
class A
{
protected:
int* x;
public:
A()
{
x=new int;
}
~A()
{
delete(x);
}
void getdata()
{
cin>>(*x);
}
};
class B:public A
{
protected:
int* y;
public:
B()
{
y=new int;
}
~B()
{
delete(y);
delete(x);
}
void getdata()
{
cin>>*y>>*x;
}
void putdata()
{
cout<<*x<<*y<<endl;
}
};
int main()
{
B b;
b.getdata();
b.putdata();
}
OUTPUT:
EXPERIMENT NO:9.1

Create a base class called shape, use this class to store two double type
values that could be used to compute the area of that shape. Derive the
specific class called TRIANGLE and RECTANGLE from the class shape.
Add to base class, a member function get_ data ( ) to initialize base class
data members and another member function display_area( ) to compute
and display the area of the figure. Make display_area() as a virtual
function and redefine function in the derived classes to suit their
requirements. Using these 3 classes design a program that will accept
dimension of RECTANGLE or TRIANGLE interactivity and display the
area.
#include<iostream>
using namespace std;
class shape
{
protected:
double x;
double y;
public:
void getdata(double z=0,double w=0)
{
x=z;
y=w;
}
virtual void display_area()=0;
};
class rectangle:public shape
{
public:
void display_area()
{
cout<<x*y<<endl;
}
};
class triangle:public shape
{
public:
void display_area()
{
cout<<0.5*x*y<<endl;
}
};
int main()
{
shape* ptr;
rectangle r;
triangle t;
ptr=&r;
ptr->getdata(3.6,4.7);
ptr->display_area();
ptr=&t;
ptr->getdata(2,8.7);
ptr->display_area();
}
OUTPUT:
Experiment no:9.2

Create a base class Employee. The class contains virtual functions


raiseSalary() and promote(). Different types of employees
like Manager, Engineer may have their own implementations of the
virtual functions present in base class Employee. Inherit class Manager
and Engineer from the base class Employee and demonstrate dynamic
polymorphism so that specific information of manager and engineer can
be displayed using pointer to base class.
#include<iostream>
#include<string>
using namespace std;
class Employee
{
protected:
string name;
int employee_id;
int salary;
public:
void getdata()
{
cin>>name>>employee_id>>salary;
}
void show()
{
cout<<name<<endl;
cout<<employee_id<<endl;
cout<<salary<<endl;
}
virtual void raise_salary()=0;
virtual void promote()=0;
};
class Manager:public Employee
{
public:
void raise_salary()
{
salary+=10000;
}
void promote()
{
cout<<"congratulations you are promoted to executive manager"<<endl;
}
};
class Engineer:public Employee
{
public:
void raise_salary()
{
salary+=5000;
}
void promote()
{
cout<<"congratulations you are promoted to deputy engineer"<<endl;
}
};
int main()
{
Employee* emp;
Engineer e;
Manager m;
emp=&e;
emp->getdata();
emp->raise_salary();
emp->promote();
emp->show();
emp=&m;
emp->getdata();
emp->raise_salary();
emp->promote();
emp->show();
}
OUTPUT:
EXPERIMENT NO:9.3

Imagine the same publishing company as described in the exercise 4 in


the previous section. Write a main( ) program that creates an array of
pointers to publication. In a loop ask the user for data about a particular
book or tape and use new to create an object of type book or tape to hold
the data. Put the pointer to the object in the array. When the user has
finished entering the data for all books and tapes, display the resulting
data for all the books and tapes entered, using a base class pointer that
points to different inherited objects and a single statement such as
pubarr[i]→ putdata( ); to display the data from each object in the array .

#include<iostream>
#include<string>
using namespace std;
class publication
{
protected:
string title;
float price;
public:
virtual void getdata()=0;
virtual void putdata()=0;
};
class book:public publication
{
private:
int pagecount;
public:
void getdata()
{
cin>>title>>price>>pagecount;
}
void putdata()
{
cout<<title<<" "<<price<<" "<<pagecount<<endl;
}
};
class tape:public publication
{
private:
int playingtime;
public:
void getdata()
{
cin>>title>>price>>playingtime;
}
void putdata()
{
cout<<title<<" "<<price<<" "<<playingtime<<endl;
}
};
int main()
{
publication* pub[5];
for(int i=0;i<5;i++)
{
pub[i]=new book;
pub[i]->getdata();
}
for(int i=0;i<5;i++)
{
pub[i]->putdata();
}
}
EXPERIMENT NO:10.1

Create a template class named Array, take private data members


according to the requirements. Public methods are given below-
(f) Constructor
(g) Destructor
(h) Copy constructor
(i) binarySearch()
(j) anySortingTechnique()

#include<iostream>
using namespace std;
template<class T>
class Array{
private:
int length;
T *arr;
public:
Array(int x)
{
int i;
length=x;
arr=new T[length];
for(i=0;i<length;i++)
arr[i]=0;
}
Array(T* a,int x)
{
int i;
length=x;
arr=new T[length];
for(i=0;i<length;i++)
arr[i]=a[i];
}
~Array()
{
delete [] arr;
length=0;
cout<<"destruction is happened";
}
Array(Array& obj)
{
obj.length=length;
obj.arr=arr;
}
void binarysrh()
{
int search;
int i,first;
int last;
int middle;
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = length-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;

}
else if(arr[middle] == search)
{
cout<<search<<" found at location "<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the list.";
}
}
void bubble()
{
int i,j;
T temp;
for(i=0;i<length-1;i++)
{
for(j=length-1;i<j;j--)
{
if(arr[j]<arr[j-1])
{
temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
}
}
}
}
void display()
{
int i;
for(i=0;i<length;i++)
{
cout<<arr[i]<<"\t";
}
}
};
int main()
{
int x[5]={1,2,6,8,9};
float y[5]={1.1,2.2,5.7};
Array <int> a1(x,5);
Array <float> a2(y,5);
cout<<"a1 is:";
a1.display();
cout<<endl;
cout<<"a2 is :";
a2.display();
cout<<endl;
a1.binarysrh();
a1.bubble();
cout<<"a1 now is :"<<endl;
a1.display();
return 0;

}
OUTPUT:
EXPERIMENT NO:10.2

Write a template class, set, that implements a set. A set is an unordered


collection of zero or more elements with no duplicates. The public
functions are to be:

g) Constructor

h) Destructor

i) Add an element

j) List the elements

k) Intersection. An intersection of two sets is another se that contains


the common elements from the two sets.

l) Union. A union of two sets is another set that contains the elements
in either the first set or the second.

m) Subtraction

SOURCE CODE:

#include<iostream>
#include<conio.h>
#include<vector>
using namespace std;

template<typename T>
class Set
{
private:
vector<T> data;
public:
Set()
{
data.clear();
}

~Set()
{
data.clear();
}

void Add_Element(T Item)


{
bool found = false;
for (int x = 0;x<data.size();x++)
if (Item == data.at(x))
{
found = true;
break;
}
if (!found)
data.push_back(Item);
}

bool IsNull() { return data.size() == 0; }

Set Union(Set& set2)


{
Set temp;
for (int x = 0;x < data.size();x++)
temp.data.push_back(data.at(x));
for (int x = 0;x < set2.data.size();x++)
{
bool found = false;
for (int y = 0;y < temp.data.size();y++)
{
if (set2.data.at(x) == temp.data.at(y))
{
found = true;
break;
}
}
if (!found)
temp.data.push_back(set2.data.at(x));
}
return temp;
}
Set Intersect(Set& set2)
{
Set temp;
for (int x = 0;x < data.size();x++)
{
for (int y = 0;y < set2.data.size();y++)
{
if (data.at(x) == set2.data.at(y))
{
temp.data.push_back(data.at(x));
break;
}
}
}
return temp;
}
Set Subtract(Set& Set2)
{
Set temp;
for (int x = 0;x < data.size();x++)
{
bool found = false;
for (int y = 0;y < Set2.data.size();y++)
{
if (data.at(x) == Set2.data.at(y))
{
found = true;
break;
}
}
if (!found)
temp.data.push_back(data.at(x));
}
return temp;
}

void display()
{
for (int x = 0;x < data.size();x++)
cout << data.at(x) << "\t";
}
};

int main()
{
Set<int> set1, set2;
set1.Add_Element(10);
set1.Add_Element(20);
set1.Add_Element(30);
set1.Add_Element(40);
set1.Add_Element(50);
set1.Add_Element(60);

set2.Add_Element(15);
set2.Add_Element(25);
set2.Add_Element(35);
set2.Add_Element(45);
set2.Add_Element(55);
set2.Add_Element(20);

cout << "Set 1:\n";


set1.display();
cout << "\n\nSet 2:\n";
set2.display();

cout << "\n\nIntersection:\n";


set1.Intersect(set2).display();

cout << "\n\nUnion:\n";


set1.Union(set2).display();

cout << "\n\nSubtraction:\n";


set1.Subtract(set2).display();

getch();
return 0;
}

OUTPUT:
EXPERIMENT NO:11.1

Create a class distance as described in the previous exercise. Include


member functions getdist( ) and display to input and output the
distances. Get a number of distance values from the user and write them
to a disk file. Append them to existing values in the file, if any. When the
user signals that no more values will be input, read the file and display
all the values.
#include<fstream>
#include<iostream>
using namespace std;
class Distance
{ private:
int feet;
float inches;
public:
Distance();
void getDist();
void showDist();
void Average(Distance[],int=100);
void WriteFile();
};
void Distance::WriteFile()
{
ofstream fout;
fout.open("distance.txt",ios::out|ios::app);
fout<<"Distance :"<<feet<<"feet\t"<<inches<<"inches"<<endl;
fout.close();
}
Distance::Distance()
{ feet=0; inches=0;
}
void Distance::getDist()
{ cout<<"Enter the feet part of distance:"; cin>>feet;
cout<<"Enter the inches part of distance:"; cin>>inches;
}
void Distance::showDist()
{ cout<<"Distance : "<<feet<<" feets "<<inches<<" inches ";
}
void Distance::Average(Distance a[],int n)
{ int i=0; for(i=0;i<n;i++)
{
feet=feet+a[i].feet;
inches=inches+a[i].inches;
}
inches = (12*feet) + inches;
inches=inches/n;
feet = (int)(inches/12);
inches = inches - (int(inches/12))*12;
}
int main()
{
Distance d;
char ch;
d.getDist();
d.showDist();
d.WriteFile();
ifstream fin;
fin.open("distance.txt" , ios::in);
ch=fin.get();
while((fin.eof())!=1)
{
cout<<ch;
ch=fin.get();
}

return 0;
}
EXPERIMENT NO:11.2

Write a program that emulates the DOS COPY command i.e. it should
copy the contents of a character file to another file. Invoke the program
with two command-line arguments – the source file and the destination
file. In the program, check that the user has typed the correct number of
arguments and that the file specified can be opened. The program signal
an error if the destination file already exists.
#include<fstream>
#include<iostream>
using namespace std;
class Distance
{ private:
int feet;
float inches;
public:
Distance();
void getDist();
void showDist();
void Average(Distance[],int=100);
void WriteFile();
};
void Distance::WriteFile()
{
ofstream fout;
fout.open("distance.txt",ios::out|ios::app);
fout<<"Distance :"<<feet<<"feet\t"<<inches<<"inches"<<endl;
fout.close();
}
Distance::Distance()
{ feet=0; inches=0;
}
void Distance::getDist()
{ cout<<"Enter the feet part of distance:"; cin>>feet;
cout<<"Enter the inches part of distance:"; cin>>inches;
}
void Distance::showDist()
{ cout<<"Distance : "<<feet<<" feets "<<inches<<" inches ";
}
void Distance::Average(Distance a[],int n)
{ int i=0; for(i=0;i<n;i++)
{
feet=feet+a[i].feet;
inches=inches+a[i].inches;
}
inches = (12*feet) + inches;
inches=inches/n;
feet = (int)(inches/12);
inches = inches - (int(inches/12))*12;
}

int main(int argc , char *argv[])


{
char ch;
//argv[0]=="Source file"
//argv[1]=="Destination file"
if(argc!=2)
{
cout<<"Invalid number of argument";
exit(10);
}
ifstream fin;
fin.open(argv[0],ios::in);
if(fin==NULL)
{
cout<<"Source File donot exist";
}
ofstream fout;
fout.open(argv[1],ios::out|ios::app);
if(fout==NULL)
{
cout<<"Destination file is not created";
exit(111);
}
ch=fin.get();
while(fin.eof()!=1)
{
fout<<ch;
}

return 0;
}
EXPERIMENT NO:11.3

Write a program that returns the size in bytes of a program entered on


the command line:
C> filesize program.ext

#include<fstream>
#include<iostream>
using namespace std;
class Distance
{ private:
int feet;
float inches;
public:
Distance();
void getDist();
void showDist();
void Average(Distance[],int=100);
void WriteFile();
};
void Distance::WriteFile()
{
ofstream fout;
fout.open("distance.txt",ios::out|ios::app);
fout<<"Distance :"<<feet<<"feet\t"<<inches<<"inches"<<endl;
fout.close();
}
Distance::Distance()
{ feet=0; inches=0;
}
void Distance::getDist()
{ cout<<"Enter the feet part of distance:"; cin>>feet;
cout<<"Enter the inches part of distance:"; cin>>inches;
}
void Distance::showDist()
{ cout<<"Distance : "<<feet<<" feets "<<inches<<" inches ";
}
void Distance::Average(Distance a[],int n)
{ int i=0; for(i=0;i<n;i++)
{
feet=feet+a[i].feet;
inches=inches+a[i].inches;
}
inches = (12*feet) + inches;
inches=inches/n;
feet = (int)(inches/12);
inches = inches - (int(inches/12))*12;
}

int main()
{
char ch;
int i=0;
ifstream fin;
fin.open("distance.txt",ios::in);
ch=fin.get();
while(fin.eof()!=1)
{
i++;
ch=fin.get();
}
cout<<"\nNumber of bytes:"<<i;
return 0;
}
EXPERIMENT NO:11.4

Write a program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is
replaced by a single space.
#include<fstream>
#include<iostream>
using namespace std;
class Distance
{ private:
int feet;
float inches;
public:
Distance();
void getDist();
void showDist();
void Average(Distance[],int=100);
void WriteFile();
};
void Distance::WriteFile()
{
ofstream fout;
fout.open("distance1.txt",ios::out|ios::app);
fout<<"Distance : "<<feet<<"feet "<<inches<<" inches "<<endl;
fout.close();
}
Distance::Distance()
{ feet=0; inches=0;
}
void Distance::getDist()
{ cout<<"Enter the feet part of distance:"; cin>>feet;
cout<<"Enter the inches part of distance:"; cin>>inches;
}
void Distance::showDist()
{ cout<<"Distance : "<<feet<<" feets "<<inches<<" inches ";
}
void Distance::Average(Distance a[],int n)
{ int i=0; for(i=0;i<n;i++)
{ feet=feet+a[i].feet; inches=inches+a[i].inches;
}
inches = (12*feet) + inches; inches=inches/n;
feet = (int)(inches/12);
inches = inches - (int(inches/12))*12;
}
int main()
{
Distance d;
char ch;
d.getDist();
d.showDist();
d.WriteFile();
ifstream fin;
fin.open("distance1.txt" , ios::in);
ch=fin.get();
while((fin.eof())!=1)
{
cout<<ch;
if(ch==' ')
{
cout<<ch;
ch=fin.get();
while(ch==' ')
ch=fin.get();
cout<<ch;
}
ch=fin.get();

return 0;
}
EXPERIMENT NO:11.5

A file contains a list of telephone numbers in the following form:-

John 23456
Ahmed 9856
……. ……..
The names contain only one word and the names and the telephone numbers are separated
by white spaces. Write a program to read the file and output the list in two columns. The
names should be left-justified and the numbers should be right-justified.
#include<fstream>
#include<iostream>
using namespace std;
class Telephone
{ private:
char name[20];
long long number;
public:
void getDist();
void showDist();
void WriteFile();
};
void Telephone::WriteFile()
{
ofstream fout;
fout.open("telephone.txt",ios::out|ios::app);
fout<<name<<" "<<number<<endl;
fout.close();
}
void Telephone::getDist()
{
getchar();
cout<<"Enter the name:";
cin>>name;
cout<<"Enter the number:";
cin>>number;
}
void Telephone::showDist()
{
cout<<name<<" "<<number<<"\n";
}

int main()
{
Telephone d;
char ch;
d.getDist();
d.showDist();
d.WriteFile();
ifstream fin;
fin.open("telephone.txt" , ios::in);
ch=fin.get();
while((fin.eof())!=1)
{
cout<<ch;
ch=fin.get();
}

return 0;
}
EXPERIMENT NO:12.1
1. Write a program that randomly catches exceptions. The program
generates a random number with the value of 0, 1, or 2. If the value is
0, the program does not catch any exception. If the value is 1, the
program catches only a specified list of exceptions. If the value is 2,
the program catches all of the exceptions.

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int a=10;
srand(a);
a=rand();
cout<<a<<endl;

int p;
p=a%3;
try
{
if(p==0)
cout<<"No Exception";
else if(p==1)
{

throw 1.0;
}
else if(p==2)
{
throw 2;
}
}
catch(int x)
{

cout<<"\nException int caught";


}
catch(double x)
{

cout<<"\nException caught";
}
catch(char x)
{

cout<<"\nException caught";
}
catch(...)
{

cout<<"caught exception"<<endl;
}
cout<<p;
return 0;
}
EXPERIMENT NO:12.2

Rewrite only those methods or operators in the Fraction class that can
be affected by divide by zero error. Include code to catch the divide-by-
zero error and handle it properly. Write a main() program to exercise it.

#include<iostream>
using namespace std;
class Fraction{
private:
int num;
int denom;
public:
Fraction(int x=1,int y=1)
{
try{
num=x;
if(y==0)
throw y;
else
denom=y;
}
catch(int a)
{
cout<<"denominator not be zero\n";
}
}
Fraction(Fraction& f)
{
num=f.num;
try
{
if(f.denom==0)
throw 1;
else
denom=f.denom;
}
catch(int a)
{
cout<<"denom should not be zero\n";
}
}

void getdata()
{
cout<<"enter the numerator"<<endl;
cin>>num;
cout<<"enter the denominator"<<endl;
try{
cin>>denom;
if(denom==0)
throw denom;
}
catch(...)
{

cout<<"denom should not be zero\n";


}
}
void display()
{
try{
if(denom==0)
throw denom;
else
cout<<num<<"/"<<denom<<endl;
}
catch(int a)
{
cout<<"error denom is zero \n";
}
}
};
int main()
{
Fraction f1,f2,f3;
f1.getdata();
f2.getdata();
f1.display();
f2.display();

}
EXPERIMENT NO:12.3

Rewrite only those methods or operators in the Array class that can be
affected by out of index error. Include the appropriate exception class
from standard library exception classes. Write a main program to test it.

#include<iostream>
using namespace std;
class Array
{
private:
int l;
int* arr;
int i;
void extend()
{
int* arr2;
if(i==0)
{
arr=new int;
i++;
}
else
{
arr2=new int[++i];
for(int j=0;j<=i-2;j++)
{
arr2[j]=arr[j];
}
try{
delete(arr);
if(arr!=NULL)
throw 1;
else
arr=arr2;
}
catch(int a)
{
cout<<"deletion not performed\n";
}
}
}
void contract()
{
int* arr2;
arr2=new int[--i];

for(int j=0;j<i;j++)
{
arr2[j]=arr[j];
}
delete(arr);
arr=arr2;
}
public:
Array(int x)
{
try{
arr=NULL;
l=x;
i=0;
if(arr!=NULL)
throw 2;
}
catch(int f)
{
cout<<"error exception caught\n";
}
}
Array(Array& a)
{
l=a.l;
arr=a.arr;
}
~Array()
{
try{
delete(arr);
if(arr!=NULL)
throw 'a';

}
catch(char v)
{
cout<<"error array not deleted exception caught\n";
}
}
bool append(int x)
{
if(i!=l)
{
extend();
arr[i-1]=x;
return 1;
}
else
return 0;
}
bool chop()
{
if(i!=0)
{
contract();
return 1;
}
else
{
return 0;
}
}
void show()
{
for(int j=0; j<i; j++)
{
cout<<arr[j]<<endl;
}
}

};
int main()
{
int i,a,j;
Array x(5);
while(j)
{
cout<<"select from the
following"<<endl<<"1.append"<<endl<<"2.chop"<<endl;
cin>>i;

if(i==1)
{
cout<<"enter the value\n";
cin>>a;
x.append(a);
}
if(i==2)
x.chop();
cout<<"want more operation?(0/1)\n";
cin>>j;
}

x.show();
}
EXPERIMENT NO:12.4

Write a function that allocates memory for a single data type passed as a
parameter. The function uses the new operator and returns a pointer to
the allocated memory. The function, however, catches and handles any
exceptions detected during. allocation

#include<iostream>
using namespace std;
template<class t>
t* memory(t a)
{
t *z;
try{
z=new t;
if(z!=NULL)
throw 1;
else
return z;
}
catch( int s)
{
cout<<" error memory not int allocated\n";
}
}
int main()
{
int *a;
a=memory(3);
cout<<a;
}

Vous aimerez peut-être aussi