Oops 20file[1]
Oops 20file[1]
1
INDEX
S. No. Experiment DATE
th
16 August, 2021
Write a C++ program to print your personal details name,
1. surname (single character), total marks, gender(M/F),
result(P/F) by taking input from the user.
1) Create a class called Employee that has “Empnumber‟ 24th August, 2021
and “Empname‟ as data members and member functions
getdata( ) to input data display() to output data. Write a
main function to create an array of ‟Employee‟ objects.
2.
Accept and print the details of at least 6 employees.
2) Write a program to implement a class called
ComplexNumber and write a function add() to add two
complex numbers.
Write a C++ program to swap two number by both call by
31st August, 2021
value and call by reference mechanism, using two functions
3. swap_value() and swap_reference respectively , by getting
the choice from the user and executing the user’s choice by
switch-case.
Write a C++ program to create a simple banking system in 13th September, 2021
which the initial balance and the rate of interest are read
from the keyboard and these values are initialized using the
constructor. The destructor member function is defined in
this program to destroy the class object created using
constructor member function. This program consists of
following member functions:
4.
i. Constructor to initialize the balance and rate of interest
ii. Deposit - To make deposit
iii. Withdraw – To with draw an amount
iv. Compound – To find compound interest
v. getBalance – To know the balance amount
vi. Menu – To display menu options
vii. Destructor
Write a program to accept five different numbers by 20th September, 2021
creating a class called friendfunc1 and friendfunc2 taking 2
5. and 3 arguments respectively and calculate the average of
these numbers by passing object of the class to friend
function.
th
Write a program to accept the student detail such as name and 27 September, 2021
3 different marks by get_data() method and display the name
6. and average of marks using display() method. Define a friend
class for calculating the average of marks using the method
mark_avg().
2
4th October, 2021
8. WAP to return absolute value of variable types integer and
float using function overloading.
10.
th
Write a C++ program to create three objects for a class named 27 October, 2021
pntr_obj with data members such as roll_no and name. Create
11. a member function set_data() for setting the data values and
print() member function to print which object has invoked it
using ‘this’ pointer
Write a C++ program to explain virtual function 9th November, 2021
(polymorphism) by creating a base class c_polygon which
has virtual function area(). Two classes c_rectangle and
12.
c_triangle derived from c_polygon and they have area() to
calculate and return the area of rectangle and triangle
respectively.
Write a program to explain class template by creating a 16th November, 2021
template T for a class named pair having two data members
of type T which are inputted by a constructor and a member
13.
function get-max() return the greatest of two numbers to
main. Note: the value of T depends upon the data type
specified during object creation.
16th November, 2021
Write a C++ program to illustrate:
i. Division by zero
14.
ii. Array index out of bounds exception
Also use multiple catch blocks.
3
EXPERIMENT-1
AIM - Write a C++ program to print your personal details name, surname
(single character), total marks, gender(M/F), result(P/F) by taking input from
the user.
THEORY - Class: A class in C++ is the building block, that leads to Object-
Oriented programming. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by creating an
instance of that class. A C++ class is like a blueprint for an object.
A Class is a user defined data-type which has data members and member
functions.
• Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior of
the objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
get() function is used to take the data input from the user and store in the data
members of the class, put() function is used to display the data stored in these
data members.
CODE
#include<bits/stdc++.h>
using namespace std;
class details
{
int marks;
char gender , result;
char first_name[20];
char last_name [20];
public :
void get()
{
cout<<"Enter your first name - ";
gets(first_name);
cout<<"Enter your last name - ";
cin>>last_name;
cout<<"Enter your marks out of 100 - ";
cin>>marks;
if( marks>=33)
result = 'P';
else
4
result = 'F';
cout<<"Enter your gender - M/F ";
cin>>gender;
return;
}
void put()
{
cout<<"First name - "<<first_name<<endl;
cout<<"First letter of last name - "<<last_name[0]<<endl;
cout<<"Total marks = "<<marks<<endl;
cout<<"Result is - "<<result<<endl;
cout<<"Gender is - "<<gender;
}
};
int main()
{
details s;
s.get();
s.put();
return 0;
}
OUTPUT
5
EXPERIMENT – 2
AIM - Create a class called 'Employee' that has “Empnumber‟ and “Empname‟
as data members and member functions getdata( ) to input datadisplay() to
output data. Write a main function to create an array of ‟Employee‟ objects.
Accept and print the details of at least 6 employees.
THEORY - A Class is a user defined data-type which has data members and
member functions. Data members are the data variables and member functions
are the functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior of the
objects in a Class.
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.
getdata() function is used to take the data input from the user and store in the
data members of the class, displaydata() function is used to display the data
stored in these data members.
User defined data types like classes and structures can be used similar to
primitive data types and can be used to create variables and arrays.
CODE
#include<iostream>
using namespace std;
class Employee
{
int Empnumber;
string Empname;
public :
void getdata( int num , string name)
{
Empnumber = num;
Empname = name;
return;
}
void datadisplay()
{
cout<<"Name is - "<<Empname<<endl;
cout<<"Employee number is - "<<Empnumber<<endl;
return;
}
};
int main()
{
int n;
cout<<"Enter the number of employees who details are to be displayed- ";
cin>>n;
int num;
string name;
Employee arr[n];
6
for( int i = 0 ; i<n ; i++)
{
cout<<"Enter name - ";
cin>>name;
cout<<"Enter employee number - ";
cin>>num;
}
OUTPUT
7
EXPERIMENT-3
AIM - Write a C++ program to swap two number by both call by value and call
by reference mechanism, using two functions swap_value() and swap_reference
respectively, by getting the choice from the user and executing the user’s
choice by switch-case.
THEORY - Call By Value: In this parameter passing method, values of actual
parameters are copied to function’s formal parameters and the two types of
parameters are stored in different memory locations. So any changes made
inside functions are not reflected in actual parameters of the caller.
Call by Reference: Both the actual and formal parameters refer to the same
locations, so any changes made inside the function are actually reflected in
actual parameters of the caller.
CODE
#include<iostream>
using namespace std;
void swap_value( int a , int b)
{
int temp;
temp = a;
a=b;
b= temp;
cout<<"After swapping a = "<<a<<" and b = "<<b;
return ;
}
void swap_reference( int *a , int *b)
{
int temp;
temp = *a;
*a= *b;
*b = temp;
cout<<"After swapping a = "<<*a<<" and b = "<<*b;
return ;
}
int main()
{
int a,b;
cout<<"Enter the value of a - ";
cin>>a;
cout<<"Enter the value of b - ";
cin>>b;
cout<<"Before swapping a = "<<a<<" and b = "<<b<<endl;
cout<<"1. Swap using call by value"<<endl;
cout<<"2. Swap using call by reference"<<endl;
cout<<"Enter your choice - ";
8
int n;
cin >>n;
switch(n)
{
case 1 :
swap_value(a , b);
break;
case 2 :
swap_reference( &a , &b);
break;
default :
cout<<"wrong input!";
}
return 0;
}
OUTPUT
9
EXPERIMENT- 4
AIM- Write a C++ program to create a simple banking system in which the
initial balance and the rate of interest are read from the keyboard and these
values are initialized using the constructor. The destructor member function is
defined in this program to destroy the class object created using constructor
member function. This program consists of following member functions-
10
~ClassName()
{
}
CODE
#include <iostream>
using namespace std;
#include<cmath>
class Bank{
float amount ;
float roi;
public:
Bank(float a , float b){
amount = a;
roi = b;
}
void withdraw()
{
int money;
cout << "Enter amount to withdraw " << endl;
cin >> money;
if(money> amount)
{
cout << "Insufficient Balance" << endl;
}
else
{
amount -= money;
cout << "Your Balance is : " << amount;
}
}
void getBalance(){
cout << "Your Balance is : " << amount;
}
void deposit(){
int money;
cout << "Enter amount to deposit " << endl;
cin >> money;
amount += money;
cout << "Your Balance is : " << amount;
}
void compound(){
float time;
cout << "Enter time duration" << endl;
cin >> time;
int compountInterest = (amount) * (pow((1 + (roi/100)),
time));
cout << "Compount Interest is : " << compountInterest <<
endl;
}
11
void menu(){
cout << " \n\n1.Deposit Money\n2.WithdrawMoney\n3.Calculate Compound Interest\
n4.Balance\n5.Destructor\nEnter the Number : " << endl;
}
~Bank()
{
cout << "Destructor called" << endl;
}
};
int main()
{
float a=0, b = 2;
Bank s(a, b);
s.menu();
int number;
cin >> number;
while(number != 5){
switch (number)
{
case 1 :
s.deposit();
break;
case 2 :
s.withdraw();
break;
case 3:
s.compound();
break;
case 4:
s.getBalance();
break;
case 5:
cout << "You have quit the system succesfully";
return 0;
default:
cout << "Invalid operation!! Please try again" <<
endl;
break;
}
s.menu();
cin >> number;
}
cout << "You have quit the system succesfully" << endl;
return 0;
}
12
OUTPUT
13
EXPERIMENT - 5
AIM - Write a program to accept five different numbers by creating a class
called friendfunc1 and friendfunc2 taking 2 and 3 arguments respectively and
calculate the average of these numbers by passing object of the class to friend
function.
THEORY - Friend Class A friend class can access private and protected
members of other class in which it is declared as friend. It is sometimes useful
to allow a particular class to access private members of other class. For
example, a LinkedList class may be allowed to access private members of
Node.
Friend Function Like friend class, a friend function can be given a special grant
to access private and protected members. A friend function can be:
a) A member of another class
b) A global function
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or
external classes are declared as friends of a class with protected or private data,
it lessens the value of encapsulation of separate classes in object-oriented
programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn’t become a
friend of A automatically.
3) Friendship is not inherited.
CODE
#include<iostream>
using namespace std;
class friendFunc2;
class friendFunc1
{
int a1,a2;
public:
friendFunc1(int x,int y)
{
a1=x;
a2=y;
}
friend float average(friendFunc1 f1,friendFunc2 f2);
};
class friendFunc2
{
14
int a3,a4,a5;
public:
friendFunc2(int x,int y,int z)
{
a3=x;
a4=y;
a5=z;
}
friend float average(friendFunc1 f1,friendFunc2 f2);
};
float average(friendFunc1 f1, friendFunc2 f2)
{
return (f1.a1 + f1.a2 + f2.a3 + f2.a4 + f2.a5) / 5.0;
}
int main()
{
int a,b,c,d,e;
cout<<"Enter the numbers - ";
cin>>a>>b>>c>>d>>e;
friendFunc1 obj1(a,b);
friendFunc2 obj2(c,d,e);
float ans = average(obj1, obj2);
cout << "Average : " << ans << endl;
return 0;
}
OUTPUT
15
EXPERIMENT – 6
AIM - Write a program to accept the student detail such as name and 3 different
marks by get_data() method and display the name and average of marks using
display() method. Define a friend class for calculating the average of marks
using the method mark_avg().
THEORY - Friend Class A friend class can access private and protected
members of other class in which it is declared as friend. It is sometimes useful
to allow a particular class to access private members of other class. For
example, a LinkedList class may be allowed to access private members of
Node.
CODE
#include<iostream>
using namespace std;
class student
{
int x , y , z;
string s;
public :
void get_data( int a, int b , int c , string k)
{ x = a;
y = b;
z = c;
s = k;
return;
} void put_data()
{
cout<<"The name of the student is - "<<s<<endl;
cout<<"The marks of the student are - "<<x<<" , "<<y<<" , "<<z<<endl;
}
friend float mark_avg( student m);
};
float mark_avg( student n)
{
return (n.x + n.y + n.z)/3.0;
}
int main()
{
student stu;
int a, b ,c;
string name;
cout<<"Enter the name of the student - ";
cin>>name;
cout<<"Enter the marks of the student - ";
cin>>a>>b>>c;
stu.get_data(a,b,c,name);
stu.put_data();
cout<<"The average marks of "<<name<<" are - "<<mark_avg(stu);
return 0;
}
16
OUTPUT
17
EXPERIMENT – 7
AIM - Write a C++ program to perform different arithmetic operation such as
addition, subtraction, division, modulus and multiplication using inline
function.
THEORY- C++ provides an inline functions to reduce the function call
overhead. Inline function is a function that is expanded in line when it is
called. When the inline function is called whole code of the inline function
gets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline
function may increase efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
CODE
#include<iostream>
using namespace std;
class operations
{
int i , j;
public :
void get_data(int a , int b)
{
i = a;
j = b;
return;
}
void put_data()
{
cout<<"a = "<<i<<endl;
cout<<"b = "<<j<<endl;
return;
}
inline int add()
{
return i+j;
}
inline int subtract()
{
return i-j;
}
inline int multiply()
{
18
return i*j;
}
inline int divide()
{
return i/j;
}
inline int modulus()
{
return i%j;
}
};
int main()
{
operations op;
cout<<"Enter the numbers - ";
int a , b;
cin>>a>>b;
op.get_data(a,b);
op.put_data();
cout<<"MENU - "<<endl;
fn1 :
int x;
cout<<"1. Add"<<endl;
cout<<"2. Subtract"<<endl;
cout<<"3. Multiply"<<endl;
cout<<"4. Divide"<<endl;
cout<<"5. Modulus"<<endl;
cout<<"6. Exit"<<endl;
cout<<"Enter your choice - ";
cin>>x;
switch (x)
{
case 1 :
{
cout<<"a + b = "<<op.add()<<endl;
goto fn1;
}
case 2 :
{
cout<<"a - b = "<<op.subtract()<<endl;
goto fn1;
}
case 3 :
{
cout<<"a * b = "<<op.multiply()<<endl;
goto fn1;
}
case 4 :
19
{
cout<<"a / b = "<<op.divide()<<endl;
goto fn1;
}
case 5 :
{
cout<<"a % b = "<<op.modulus()<<endl;
goto fn1;
}
case 6 :
{
return 0;
}
}
}
OUTPUT
20
EXPERIMENT-8
AIM-WAP to return absolute value of variable types integer and float using
function overloading.
THEORY - Function overloading is a feature of object oriented programming
where two or more functions can have the same name but different
parameters. When a function name is overloaded with different jobs it is
called Function Overloading. In Function Overloading “Function” name
should be the same and the arguments should be different. Function
overloading can be considered as an example of polymorphism feature in
C++.
How Function Overloading works?
• Exact match:- (Function name and Parameter)
• If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
• If no match found:
->C++ tries to find a match through the standard conversion.
•ELSE ERROR
CODE
#include<bits/stdc++.h>
using namespace std;
int absolute(int m)
{
if(m>=0)
return m;
else
return -m;
}
float absolute(float m)
{
if(m>=0)
return m;
else
return -m;
}
int main()
{
cout<<"Enter the value of integer - ";
int x;
cin>>x;
cout<<"The absolute value of "<<x<<" is = "<<absolute(x)<<endl;
21
cout<<"Enter the value of float - ";
float y;
cin>>y;
cout<<"The absolute value of "<<y<<" is = "<<absolute(y)<<endl;
return 0;
}
OUTPUT
22
EXPERIMENT – 9
AIM - WAP to perform string operations using operator overloading in C++
1. String Copy
2. ==,>,<, Equality
3. + Concatenation
THEORY - In C++, we can make operators to work for user defined classes.
This means C++ has the ability to provide the operators with a special meaning
for a data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we
can concatenate two strings by just using +.
Other example classes where arithmetic operators may be overloaded are
Complex Number, Fractional Number, Big Integer, etc.
Operator functions are same as normal functions. The only differences are,
name of an operator function is always operator keyword followed by symbol of
operator and operator functions are called when the corresponding operator is
used.
Almost all operators can be overloaded except few. Following is the list of
operators that cannot be overloaded.
. (dot) ?: :: sizeof
Important points about operator overloading
1) For operator overloading to work, at least one of the operands must be a user
defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment
operator with every class. The default assignment operator does assign all
members of right side to the left side and works fine most of the cases (this
behaviour is same as copy constructor). See this for more details.
3) Conversion Operator: We can also write conversion operators that can be
used to convert one type to another type.
Overloaded conversion operators must be a member method. Other operators
can either be member method or global method.
4) Any constructor that can be called with a single argument works as a
conversion constructor, means it can also be used for implicit conversion to the
class being constructed.
CODE
#include <iostream>
#include <stdio.h> //for gets() and puts()
#include <string.h>
using namespace std;
23
class String{
string str;
public:
String()
{
str = "";
}
String(string s)
{
str = s;
}
void operator=(String s);
String operator+(String s);
bool operator==(String s);
bool operator<(String s);
bool operator>(String s);
void show();
};
24
else if(str[i] > s.str[i])
return false;
}
return false;
}
int main(){
String s1("Priyanshi"), s2("Anand"), ch;
cout<<"String s1 - ";
s1.show();
cout<<"String s2 - ";
s2.show();
s1 = s1 + s2;
ch = s1;
cout<<"String s1 after concatenation - ";
s1.show();
ch.show();
if(s1 < s2)
cout <<"s2 is longer than s1!";
else
cout <<"s1 is longer than s2!";
return 0;
}
OUTPUT
25
EXPERIMENT – 10
AIM - Consider a class network of figure given below. The class master
derives information from both account and admin classes which in turn derive
information from the class person. Define all the four classes and write a
program to create, update and display the information contained in master
objects. Also demonstrate the use of different access specifiers by means of
member variables and member functions.
THEORY - In C++, inheritance is a process in which one object acquires all the
properties and behaviours of its parent object automatically. In such way, you can
reuse, extend or modify the attributes and behaviours which are defined in other
class.
In C++, the class which inherits the members of another class is called derived
class and the class whose members are inherited is called base class. The derived
class is the specialized class for the base class.
Advantage of C++ Inheritance
Code reusability: Now you can reuse the members of your parent class. So, there
is no need to define the member again. So, less code is required in the class.
Types Of Inheritance
C++ supports five types of inheritance:
o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
class derived_class_name :: visibility-mode base_class_name
{
// body of the derived class.
}
26
Where,
derived_class_name: It is the name of the derived class.
visibility mode: The visibility mode specifies whether the features of the base
class are publicly inherited or privately inherited. It can be public or private.
base_class_name: It is the name of the base class.
o When the base class is privately inherited by the derived class, public
members of the base class become the private members of the derived
class. Therefore, the public members of the base class are not accessible by
the objects of the derived class only by the member functions of the derived
class.
o When the base class is publicly inherited by the derived class, public
members of the base class also become the public members of the derived
class. Therefore, the public members of the base class are accessible by the
objects of the derived class as well as by the member functions of the base
class.
Note:
o In C++, the default mode of visibility is private.
o The private members of the base class are never inherited.
CODE
#include<iostream>
using namespace std;
class person{
private:
string name;
int code;
public:
person(string s, int c){
name = s;
code = c;
cout<<"\nPerson constructor called";
}
void display();
void updateName(string);
void updateCode(int);
};
class account: virtual public person{
private:
int pay;
public:
account(string s, int c, int p):person(s, c){
pay = p;
cout<<"\nAccount constructor called";
}
void display();
void updatePay(int);
};
27
class admin: virtual public person{
private:
int experience;
public:
admin(string s, int c, int exp):person(s, c){
experience = exp;
cout<<"\nAdmin constructor called";
}
void display();
void updateExp(int);
};
class master: public account, public admin{
public:
master(string s, int c, int p, int
exp):account(s,c,p),admin(s,c,exp),person(s, c){
cout<<"\nMaster constructor called";
}
void update();
void display();
};
void person :: display(){
cout<<"\nName = "<<name;
cout<<"\nCode = "<<code;
}
void person :: updateName(string s){
name = s;
}
void person :: updateCode(int n){
code = n;
}
void account :: display(){
cout<<"\nPay = "<<pay;
}
void account :: updatePay(int n){
pay = n;
}
void admin :: display(){
cout<<"\nExperience = "<<experience;
}
void admin :: updateExp(int n){
experience = n;
}
void master :: update(){
//this->display();
cout<<"\n\nUPDATE DETAILS";
string n;
int c, p, exp;
28
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
updateName(n);
updateCode(c);
updatePay(p);
updateExp(exp);
}
void master :: display(){
cout<<"\n\nMASTER DETAILS";
person::display();
account::display();
admin::display();
}
int main(){
//master M;
string n;
int c, p, exp;
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
master M(n,c,p,exp);
M.display();
M.update();
M.display();
return 0;
}
OUTPUT
29
EXPERIMENT-11
AIM- Write a C++ program to create three objects for a class named pntr_obj
with data members such as roll_no and name. Create a member function
set_data() for setting the data values and print() member function to print which
object has invoked it using ‘this’ pointer.
THEORY - Every object in C++ has access to its own address through an
important pointer called this pointer. this pointer is an implicit parameter to all
member functions. Therefore, inside a member function, this may be used to
refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of
a class. Only member functions have a this pointer.
o It can be used to pass current object as a parameter to another
method.
o It can be used to refer current class instance variable.
o It can be used to declare indexers.
CODE
#include<bits/stdc++.h>
using namespace std;
class prn_obj
{
int rno;
string name;
public:
void set_data(string n, int r)
{
name=n;
rno=r;
}
void print() {
cout<<this->name<<" has invoked print() function"<<endl;
cout<<"The roll number is "<<this->rno<<endl;
}
};
int main()
{
prn_obj ob1,ob2,ob3;
ob1.set_data("Priyanshi",1);
ob2.set_data("Sandali",2);
ob3.set_data("Anjali",3);
ob1.print();
ob2.print();
ob3.print();
return 0;
}
30
OUTPUT
31
EXPERIMENT -12
AIM - Write a C++ program to explain virtual function (polymorphism) by
creating a base class c_polygon which has virtual function area(). Two classes
c_rectangle and c_triangle derived from c_polygon and they have area() to
calculate and return the area of rectangle and triangle respectively.
THEORY –
1. A virtual function is a member function which is declared in
the base class using the keyword virtual and is re-defined (Overriden) by
the derived class.
2. The term Polymorphism means the ability to take many forms. It occurs
if there is a hierarchy of classes which are all related to each other
by inheritance.
Consider the following simple program as an example of runtime
polymorphism. The main thing to note about the program is that the derived
class’s function is called using a base class pointer. The idea is that virtual
functions are called according to the type of the object instance pointed to or
referenced, not according to the type of the pointer or reference. In other words,
virtual functions are resolved late, at runtime.
CODE
#include<bits/stdc++.h>
using namespace std;
class c_polygon
{
public :
virtual float area() = 0;
};
class c_triangle : public c_polygon
{
float a,b,c;
public :
c_triangle(){}
void setSides(float x , float y , float z)
{
a=x;
b=y;
c=z;
}
float area()
{
float s = (a+b+c)/2;
float ans = sqrt(s*(s-a)*(s-b)*(s-c));
32
return ans;
}
};
class c_rectangle : public c_polygon
{
float l,b;
public :
c_rectangle(){}
void setSides(float x , float y )
{
l=x;
b=y;
}
float area()
{
return l*b;
}
};
int main()
{
cout<<"Enter the sides of the triangle : ";
c_triangle tri;
float a,b,c;
cin>>a>>b>>c;
tri.setSides(a,b,c);
cout<<"Area of the triangle with sides "<<a<<" , "<<b<<" , "<<c<<" =
"<<tri.area()<<endl;
cout<<"Enter the sides of the rectangle : ";
c_rectangle rect;
float l,w;
cin>>l>>w;
rect.setSides(l,w);
cout<<"Area of the rectangle with sides "<<l<<" , "<<w<<" =
"<<rect.area()<<endl;
}
OUTPUT
33
EXPERIMENT -13
AIM- Write a program to explain class template by creating a template T for a
class named pair having two data members of type T which are inputted by a
constructor and a member function get-max() return the greatest of two numbers
to main. Note: the value of T depends upon the data type specified during object
creation.
THEORY - C++ adds two new keywords to support
templates: ‘template’ and ‘typename’. The second keyword can always be
replaced by keyword ‘class’.
Templates are expanded at compiler time. This is like macros. The difference is,
the compiler does type checking before template expansion. The idea is simple,
source code contains only function/class, but compiled code may contain
multiple copies of same function/class.
Class Templates Like function templates, class templates are useful when a
class defines something that is independent of the data type. Can be useful for
classes like LinkedList, BinaryTree, Stack, Queue, Array, etc.
CODE
#include <iostream>
using namespace std;
template<class t>
class Pair
{
t a, b;
public:
Pair(t x, t y)
{
a = x;
b = y;
}
t get_max()
{
if(a>b)
return a;
else
return b;
}
};
int main(){ int a,b;
cout<<"Enter the value of two integers : ";
cin>>a>>b;
Pair <int> m(a,b);
cout<<"The max value out of "<<a<<" and "<<b<<" = "<<m.get_max()<<endl;
34
float c, d;
cout<<"Enter the value of two floats : ";
cin>>c>>d;
Pair <float> n(c ,d);
cout<<"The max value out of "<<c<<" and "<<d<<" = "<<n.get_max()<<endl;
return 0;
}
OUTPUT
35
EXPERIMENT -14
AIM- Write a C++ program to illustrate
i. Division by zero
ii. Array index out of bounds exception
Also use multiple catch blocks.
THEORY - An exception is a problem that arises during the execution of a
program. A C++ exception is a response to an exceptional circumstance that
arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to
another. C++ exception handling is built upon three keywords: try,
catch, and throw.
• throw − A program throws an exception when a problem shows up. This
is done using a throw keyword.
• catch − A program catches an exception with an exception handler at the
place in a program where you want to handle the problem.
The catch keyword indicates the catching of an exception.
• try − A try block identifies a block of code for which particular
exceptions will be activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception using
a combination of the try and catch keywords. A try/catch block is placed around
the code that might generate an exception. Code within a try/catch block is
referred to as protected code
CODE
i. Division by zero
#include <bits/stdc++.h>
using namespace std;
float CheckDenominator(float den)
{
if (den == 0)
throw "Error";
else
return den;
}
int main()
{
float numerator, denominator, result;
cout<<"Enter the numerator and denominator : ";
cin>>numerator;
cin>>denominator;
try {
if (CheckDenominator(denominator)) {
result = (numerator / denominator);
cout << "The quotient is "
36
<< result << endl;
}
}
catch (...) {
cout << "Exception occurred" << endl;
}
}
ii. Array index out of bounds exception
#include <bits/stdc++.h>
using namespace std;
int main () {
try
{
char * mystring;
mystring = new char [10];
if (mystring == NULL) throw "Allocation failure";
for (int n=0; n<=100; n++)
{
if (n>9) throw n;
mystring[n]='z';
}
}
catch (int i)
{
cout << "Exception: ";
cout << "index " << i << " is out of range" << endl;
}
catch (char * str)
{
cout << "Exception: " << str << endl;
}
return 0;
}
OUTPUT
i. Division by zero
37
38