Академический Документы
Профессиональный Документы
Культура Документы
LTPC
EID 221 0 0 3 2
C++ LABORATORY
MANUAL
Prepared by:
Sri T.Srikanth
Smt. T. Kalaichelvi
Sri G.K Vasudevarao
Ms. Y. Divya Bharathi
Course Outcomes:
1. Write a program that contains a function to exchange (swap) values of two arguments by
using pointers and References parameters.
2. Write a program to check the given string is palindrome or not using a private member
function.
3. Write a program to find transpose of 2-D matrix by allocating memory dynamically to the
matrix. Initialize and display contents of the matrix and deallocate memory.
4. Write a program to add corresponding elements of two 2-D matrices using friend
function. Create two classes each capable of storing one 2-D matrix. Declare the matrices
under private access specifier and access them outside the class.
5. Write a program for finding area of different geometric shapes (Circle, Rectangle and
Cube) using function overloading.
6. Write a Program to generate Fibonacci Series by using Constructor to initialize the Data
Members.
7. Write a program to add two matrices of same copy. Create two objects of the class and
each of which refers to one 2-D matrix. Use constructor to allocate memory dynamically
and use copy constructor to allocate memory when one array object is used to initialize
another.
8. Write a program to demonstrate single inheritance distinguishing public and private
derivation.
9. Write a program to illustrate the implementation of both Multilevel and Multiple (Hybrid)
inheritance.
10. Write a program to find transpose of a given matrix of mxn size using unary operator
overloading.
11. Write a program to add two matrices of mxn size using binary operator overloading.
12. Write a program to demonstrate the usage of virtual functions.
13. Write a program to sort a given set of elements using function template.
14. Write a program to search a key element in a given set of elements using class template.
15. Write a program to find average marks of the subjects of a student. Throw multiple
exceptions and define multiple catch statements to handle division by zero as well as array
index out of bounds exceptions.
****
1. Write a program that contains a function to exchange values of two
arguments by using pointers and References parameters.
Reference variable:
A reference variable is an alias, that is, another name for an already existing
variable. Once a reference is initialized with a variable, either the variable name
or the reference name may be used to refer to the variable.
Syntax:
Example:
int a = 10;
int & b = a; // b is a reference variable of a
References Pointers
Advantages of References:
#include<iostream>
using namespace std;
void swap (int &a, int &b) // &a and &b are reference variables
{
int temp;
temp=a;
a=b;
b=temp;
}
int main()
{
int i=5,j=10;
cout<<"Before Swapping I = "<<i<<" J = "<<j<<endl;
swap(i,j);
cout<<"After Swapping Using Reference I = "<<i<<" J = "<<j<<endl;
cout<<"Before Swapping I = "<<i<<" J = "<<j<<endl;
swap1(&i,&j);
cout<<"After Swapping Using Pointer I = "<<i<<" J = "<<j<<endl;
}
Output:
2. Write a program to check the given string is palindrome or not using a private
member function.
Syntax:
class class_name
{
private:
return_type function_name () // private member function declaration
{
---------;
}
public:
return_type function_name () // public member function declaration
{
---------;
function_name (); // private member function calling
}
};
int main()
{
class_name object_name;
object_name.function_name(); // public member function calling
}
Progam:
#include<iostream>
#include<string.h>
using namespace std;
class palinstr
{
private:
char input[30];
int checkpalin(char fninput[20]);
public:
void palin();
};
void palinstr::palin()
{
cout<<"Enter a String: ";
cin>>input;
if(checkpalin(input))
cout<<input<<" is a Palindrome\n";
else
cout<<input<<" is not a Palindrome\n";
}
int main()
{
palinstr sp;
sp.palin();
}
Output:
3. Write a program to find transpose of 2-D matrix by allocating
memory dynamically to the matrix. Initialize and display contents of the matrix
and deallocate memory
Dynamic memory is allocated using operator new. new is followed by a data type
specifier and, if a sequence of more than one element is required, the number of
these within brackets []. It returns a pointer to the beginning of the new block of
memory allocated.
Syntax:
The first expression is used to allocate memory to contain one single element of
type type.
The second one is used to allocate a block (an array) of elements of type type,
where “number of elements” is an integer value representing the amount of
memory required.
Program:
#include<iostream>
using namespace std;
class trans
{
int **a,**b;
int m,n;
public:
void initialize();
void transpose();
void display();
void deallocate();
};
void trans::initialize()
{
int i,j;
cout<<"No. of Rows and Columns: ";
cin>>m>>n;
a=new int *[m]; // create input matrix
for(i=0; i<m; i++)
a[i]=new int[n];
cout<<"Enter elements:\n";
for(i=0; i<m; i++)
for(j=0; j<n; j++)
cin>>a[i][j];
Friend Function:
A friend function of a class is defined outside that class scope but it has the right
to access all private and protected members of the class.
Syntax:
class class_name
{
private:
//private members declaration;
public:
return_type function_name () // public member function
{
---------;
}
friend return_type function_name (class_name object_name); // friend
function declaration
};
return_type function_name (); // friend function derivation
{
---------;
}
int main()
{
class_name object_name;
object_name.function_name(); // public member function calling
function_name(object_name); // friend function calling
}
Program:
include<iostream>
using namespace std;
class matrix2;
class matrix1
{
int a[5][5];
int m,n;
public:
void getmatrix1();
void putmatrix1();
friend void matrixsum(matrix1,matrix2);
};
void matrix1::getmatrix1()
{
int i,j;\
cout<<"MATRIX 1:\n";
cout<<"Rows and Columns: ";
cin>>m>>n;
cout<<"Enter elements:\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
}
void matrix1::putmatrix1()
{
int i,j;
cout<<"MATRIX 1:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
class matrix2
{
int b[5][5];
int m,n;
public:
void getmatrix2();
void putmatrix2();
friend void matrixsum(matrix1,matrix2);
};
void matrix2::getmatrix2()
{
int i,j;
cout<<"MATRIX 2:\n";
cout<<"Rows and Colums: ";
cin>>m>>n;
cout<<"Enter elements:\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>b[i][j];
}
void matrix2::putmatrix2()
{
int i,j;
cout<<"MATRIX 2:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<b[i][j]<<" ";
cout<<endl;
}
}
int i,j;
if(g.m==h.m && g.n==h.n)
{
cout<<"SUM OF MATRICES:\n";
for(i=0;i<g.m;i++)
{
for(j=0;j<g.n;j++)
cout<<g.a[i][j]+h.b[i][j]<<" ";
cout<<endl;
}
}
else
cout<<"Dimensions are not same...Addition not possible";
}
int main()
{
matrix1 m1;
matrix2 m2;
m1.getmatrix1();
m2.getmatrix2();
m1.putmatrix1();
m2.putmatrix2();
matrixsum(m1,m2);
}
Output:
5. Write a program for finding area of different geometric shapes (Circle,
Rectangle and Cube) using function overloading
Function Overloading:
If any class has multiple functions with same names but different
parameters then they are said to be overloaded. Function overloading allows you
to use the same name for different functions, to perform, either same or different
functions in the same class.
Function overloading is usually used to enhance the readability of the
program. If you have to perform one single operation but with different number
or types of arguments, then you can simply overload the function.
Function overloading can be done in 2 ways.
i. By changing number of Arguments.
ii. By having different types of argument
Syntax:
return_type Function_Name (Parameter1, Parameter2)
{
-------;
}
return_type Function_Name (Parameter1, Parameter2, Parameter3)
{
-------;
}
int main()
{
function_name (Parameter1, Parameter2); // Function with 2 parameter will be called
Program:
#include<iostream>
using namespace std;
float area(int r) // circle function
{
return (3.14159*r*r);
}
float area(float a) // cube function
{
return (6*a*a);
}
int area(int l,int b) // rectangle function
{
return (l*b);
}
int main()
{
int radius,length,breadth;
float side;
cout<<"Radius of Circle: ";
cin>>radius;
cout<<"Length of Side of Cube: ";
cin>>side;
cout<<"Length and Breadth of Rectangle: ";
cin>>length>>breadth;
cout<<"Area of Circle: "<<area(radius)<<"\n";
cout<<"Area of Cube: "<<area(side)<<"\n";
cout<<"Area of Rectangle: "<<area(length,breadth)<<"\n";
}
Output:
6. Write a program to generate Fibonacci Series using Constructor to
initialize the data members?
Constructor:
A constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting initial
values for certain member variables. It can be overloaded.
Syntax:
class class_name()
{
public:
class_name() //Constructor Member Function
{
-----------; //Initialization of the constructor
}
return_type function_name() //Normal Member Function
{
-----------;
}
};
int main()
{
class_name object_name; //Constructor Calling
object_name.function_name(); //Member Function Calling
}
Program:
#include<iostream>
#include<iomanip>
using namespace std;
class fibonacci
{
int n1,n2;
public:
fibonacci()
{
n1 = 0;
n2 = 1;
}
void series(int);
};
void fibonacci::series(int n)
{
int i,next;
cout<<setw(4) << n1 <<setw(4) << n2;
for(i=1; i<= n-2; i++)
{
next = n1 + n2;
cout<<setw(4) << next;
n1 = n2;
n2 = next;
}
}
int main()
{
fibonacci fib;
int n;
cout<< "FIBONACCI SERIES\n";
cout<< "How many numbers? ";
cin>> n;
fib.series(n);
}
Output:
7. Write a program to add two matrices of same copy. Create two objects of the
class and each of which refers one 2D matrix. Use constructor to allocate
memory dynamically and use copy constructor to allocate memory when one
array object is used to initialize another.
Copy Constructor:
The copy constructor is a constructor which creates an object by initializing it
with an object of the same class, which has been created previously. The copy
constructor is used to:
• Initialize one object from another of the same type.
• Copy an object to pass it as an argument to a function.
• Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then it
is a must to have a copy constructor.
Syntax:
classname (const classname &obj)
{
// body of constructor
}
Here, obj is a reference to an object that is being used to initialize another object.
Program:
#include<iostream>
using namespace std;
class matrix
{
int **a;
public:
matrix() // Dynamic Constructor
{
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
a[i]=new int[3];
cout<<"Enter elements for a 3x3 matrix:\n";
for(i=0; i<3; i++)
for(j=0; j<3; j++)
cin>>a[i][j];
}
matrix(matrix & x) // Copy Constructor
{
int i,j;
a=new int*[3];
for(i=0; i<3; i++)
a[i]=new int[3];
for(i=0; i<3; i++)
for(j=0; j<3; j++)
a[i][j]=x.a[i][j];
}
~matrix() // Destructor
{
int i;
for(i=0; i<3; i++)
delete a[i];
delete a;
}
void putmatrix();
friend void add(matrix,matrix);
};
void matrix::putmatrix()
{
int i,j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
int main()
{
matrix obj1;
matrix obj2(obj1);
cout<<"Matrix 1 (and Matrix 2 also):\n";
obj1.putmatrix();
cout<<"SUM of the Matrices:\n";
add(obj1,obj2);
}
Output:
8. Derived class accessing private members of base class with public
inheritance
Inheritance:
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called the base
class, and the new class is referred to as the derived class.
A class can be derived from more than one classes, which means it can inherit
data and functions from multiple base classes. To define a derived class, we use a
class derivation list to specify the base class
private:
Private is the highest level of data-hiding. Not only are the functions and variables
marked private not accessible by code outside the specific object in which that
data appears, but private variables and functions are not inherited.
public:
The most open level of data hiding is public. Anything that is public is available to
all derived classes of a base class, and the public variables and data for each
object of both the base and derived class is accessible by code outside the class.
Functions marked public are generally those the class uses to give information to
and take information from the outside world.
protected:
Syntax:
class base_class_name
{
public:
base_class_nember() // base class member function
{
}
};
class derived_class_name : access_specifier base_class_name
{
public:
derived_class_nember() // derived class member function
{
}
};
int main()
{
derived_class_name object_name;
object_name.base_class_nember();
object_name.derived_class_nember();
}
Program:
#include<iostream>
using namespace std;
class emp
{
private:
{
get(); //Base_class_Private_Member_Function_calling
}
};
public:
void get1()
{
callget(); // Base_class_Public_Member_Function_calling
cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
void display()
{
cout<<"ENO\tENAME\tDESIGNATION\tBASICPAY\tHRA\tDA
\tPF\tNETPAY\n";
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t\t"<<bp<<"\t\t"
<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<np<<"\n";
}
};
int main()
{
salary s;
s.get1(); // Derived_class_Public_Member_Function_calling
s.calculate();
s.display();
}
Output:
9. Write a C++ program to implement Hybrid Inheritance
Hybrid Inheritance:
Hybrid Inheritance is a method where one or more types of inheritance are
combined together and used.
Hybrid inheritance is a combination of multiple inheritance and multilevel
inheritance. A class is derived from two classes as in multiple inheritance.
However, one of the parent classes is not a base class. It is a derived class.
Syntax:
class base_class_name1 //Base Class1
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class derived_class_name1:public base_class_name1 // Derived class1 inherits
Base Class1 as Public
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class base_class_name2 //Base Class2
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
class derived_class_name2: public derived_class_name1, public base_class_name2
// Derived class2 inherits Derived Class1 & Base Class2 as Public
{
protected:
Data Member;
public:
Member Fuction()
{
}
};
int main()
{
derived_class_name2 object_name;
object_name.Base_class1_Member Fuction();
object_name.Derived_class1_Member Fuction();
object_name.Base_class2_Member Fuction();
object_name.Derived_class2_Member Fuction();
}
Program:
#include<iostream>
using namespace std;
class stu //Base Class1
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
cout<<"Roll No:"<<rno<<"\n";
}
};
class test:public stu // Derived class1 inherits Base Class1 as Public
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks Obtained:"<<"\nPart1="<<part1<<"\n"<<"Part2="
<<part2<<"\n";
}
};
class sports //Base Class2
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"\nSports:"<<score<<"\n";
}
};
class result: public test, public sports // Derived class2 inherits Derived Class1 &
Base Class2 as Public
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"\nTotal Score="<<total<<"\n";
}
int main()
{
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}
Output:
10. C++ program to find transpose of a given matrix of m*n size using binary
operator overloading
Operator overloading:
• The meaning of operators are already defined and fixed for basic types like:
int, float, double etc in C++ language.
• For example: If you want to add two integers then, + operator is used. But, for
user-defined types(like: objects), you can define the meaning of operator, i.e,
you can redefine the way that operator works.
• For example: If there are two objects of a class that contain string as its data
member, you can use + operator to concatenate two strings.
• Suppose, instead of strings if that class contains integer data member, then
you can use + operator to add integers.
• This feature in C++ programming that allows programmer to redefine the
meaning of operator when they operate on class objects is known as operator
overloading.
Syntax:
class < class_name>
{
Return_type operator <sign>(argument )
{
// body of function
}
};
Program:
#include<iostream>
using namespace std;
class matrix
{
int x[5][5],m,n;
public:
matrix(int a,int b)
{
m=a;n=b;
}
void get();
void put();
matrix operator !();
};
void matrix::get()
{
int i,j;
cout<<"\n Enter a matrix of order"<<m<<"x"<<n<<"\n";
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>x[i][j];
}
void matrix::put()
{
int i,j;
Output:
11. Write a program to add two matrices of mxn size using binary operator
overloading.
Binary Operator Overloading:
• To overload a operator, a operator function is defined inside a class.
• Binary operators are addition (+) operator, subtraction (-) operator and
division (/) operator.
Syntax:
class < class_name>
{
Return_type operator <sign>(argument )
{
// body of function
}
};
Program:
#include<iostream>
using namespace std;
class matrixadd
{
int m, n, x[30][30];
public:
matrixadd() // Default Constructor
{
}
matrixadd(int a, int b) // Parameterized Constructor
{
m=a;
n=b;
}
void getdata();
void putdata();
matrixadd operator +(matrixadd);
};
void matrixadd:: getdata() //Input Function to get the values of first Matrix
{
cout<<"\nEnter values into the matrix :\n";
for(int i=0; i<m; i++)
{
for(int j=0; j<n;j++)
{
cin>>x[i][j];
}
}
Output:
12. Write a program to demonstrate the usage of virtual functions.
Virtual Function:
• A virtual function is a member function that is declared within a base class and
redefined by a derived class.
• To create virtual function, precede the function’s declaration in the base class
with the keyword “virtual”.
• When a class containing virtual function is inherited, the derived class
redefines the virtual function to suit its own needs.
• Base class pointer can point to derived class object.
• In this case, using base class pointer if we call some function which is in both
classes, then base class function is invoked.
• But if we want to invoke derived class function using base class pointer, it can
be achieved by defining the function as virtual in base class, this is how virtual
functions support runtime polymorphism.
Syntax:
class <Base_class_name>
{
virtual ret-type func-name( )
{
// body of function
}
};
Program:
#include<iostream>
using namespace std;
class base
{
public:
void display()
{
cout<<"\n\t\tBase class display." ;
}
virtual void show()
{
cout<<"\n\t\tBase class show.";
}
};
class drived:public base
{
public:
void display()
{
cout<<"\n\t\tDrived class display.";
}
void show()
{
cout<<"\n\t\tDrived class show.";
}
};
int main()
{
base obj1;
base *p;
cout<<"\nP points to base class:\n" ;
p=&obj1;
p->display();
p->show();
Output:
13. Write a program to sort a given set of elements using function template.
Function Template
• Function Template gives the flexibility to a programmer for using any data type
in a function without rewriting the whole function for each data type again
and again.
Syntax:
template <class type>
ret_type func_name(parameter list)
{
// body of function
}
Program:
#include<iostream>
using namespace std;
template<class T>
void bubblesort(T a[], int n)
{
int i, j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
T element;
element = a[i];
a[i] = a[j];
a[j] = element;
}
}
}
}
int main()
{
int a[6]={1,2,3,4,4,0};
char b[4]={'s','b','d','e'};
cout<<”Function Template used for Integers:\n”;
bubblesort(a,6);
cout<<"\nSorted Order Integers: ";
for(int i=0;i<6;i++)
{
cout<<a[i]<<"\t";
}
cout<<”\n\nFunction Template used for Characters.\n”;
bubblesort(b,4);
cout<<"\nSorted Order Characters: ";
for(int j=0;j<4;j++)
{
cout<<b[j]<<"\t";
}
return 0;
}
Output:
14. Write a program to search a key element in a given set of elements using
class template.
Class Template:
• A template is a blueprint or formula for creating a generic class or a function.
• In template we are creating type.
• Type is the placeholder type name, which will be specified when a class is
instantiated. You can define more than one generic data type by using a
comma-separated list.
Syntax:
template <class type>
class <class_name>
{
ret_type func_name(parameter list)
{
// body of function
}
};
Program:
#include<iostream>
#include<string.h>
using namespace std;
template<class T>
class arraysearch
{
T a[30],se;
int size;
public:
void get()
{
cout<<"\n Enter the size of array :";
cin>>size;
cout<<"\n Enter "<<size<<" elements :\n";
for(int i=0;i<size;i++)
{
cin>>a[i];
}
}
void search()
{
cout<<"\n Enter the elements to search:\n";
cin>>se;
int f=0;
for(int i=0;i<size;i++)
{
if(a[i]==se)
{
f=1;
cout<<"\n Element found at position:"<<i+1;
break;
}
}
if(f==0)
{
cout<<"\n Element not found.";
}
}
};
int main()
{
arraysearch <int> in;
arraysearch <char> ch;
cout<<"\n Searching integers :";
in.get();
in.search();
cout<<"\n\n Searching characters :";
ch.get();
ch.search();
return 0;
}
Output:
15. Write a program to find average marks of the subjects of a student. Throw
multiple exceptions and define multiple catch statements to handle division by
zero as well as array index out of bounds exceptions.
Exception Handling:
• 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.
Syntax:
try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}
Program:
# include<iostream>
using namespace std;
int main()
{
int n,marks[10];
float avg=0,tot=0;
cout<<"\nEnter the no of subjects :";
cin>>n;
cout<<"\nEnter the marks of a student "<<n<<" students\n";
try
{
if(n>0&&n<=10)
{
for(int i=1;i<=n;i++)
{
cout<<"Enter marks of student"<<i<<":\t";
cin>>marks[i];
tot+=marks[i];
}
avg=tot/n;
cout<<"\nTotal marks :\t"<<tot<<"\nAverage of marks:\t"<<avg;
}
else if(n==0)
throw (0);
else if (n>10)
throw(10);
}
catch(int i)
{
cout<<"\n Divide by zero error...";
}
catch(double i)
{
cout<<"\n Array index out of bound";
}
}
Output: