Vous êtes sur la page 1sur 85

CS6311-PDS2 Lab Manual

Ex. 1a

CONSTRUCTOR

Aim
To initialize data members of objects using different types of constructors.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare class distance containing data members inch and feet.
Define default constructor that initializes data members to 0.
Define parameterized constructor that initializes data members with values provided.
Define display function to print value of data members
Create distance objects to invoke the constructors.
Call display function for each distance object.
Stop

Program
// 1a - Constructor types
#include <iostream.h>
class distance
{
int feet;
int inch;
public:
distance()
// Default constructor
{
feet = 0;
inch = 0;
}
distance (int n, int d = 0)
//Parameterized constructor
{
feet = n;
inch = d;
}
void print()
{
cout << feet << "." << inch << "ft \n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

int main()
{
distance d1, d2(4),
d1.print();
d2.print();
d3.print();
}

d3(22,7);

Output
0.0ft
4.0ft
22.7ft

Result
Thus data members of an object were automatically initialized using constructors.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 1b

COPY CONSTRUCTOR

Aim
To initialize data members of an object using copy constructor.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare class complex with data members real and imag
Define parameterized constructor that initializes data members with given values
Define copy constructor that uses an object reference to initialize data members of
another object
Define display function to print data members
Create complex objects that invoke copy constructor in various ways.
Call display function for each distance object.
Stop

Program
// 1b Copy Constructor
#include <iostream.h>
class complex
{
int real;
int imag;
public:
complex(int r, int i)
{
real = r;
imag = i;
}
complex(const complex &c1)
{
real = c1.real;
imag = c1.imag;
}

// copy constructor

void display()
{
cout << real << " + " << imag << "i \n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

int main()
{
complex c1(2,3), c2(6, -2);
complex c3 = c1;
// copy constructor is invoked
complex c4(c2);
// copy constructor is invoked
c3.display();
c4.display();
return 0;
}

Output
2 + 3i
6 + -2i

Result
Thus data members of an object is initialized using another object.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 1c

DESTRUCTOR

Aim
To allocate memory for objects dynamically and release memory using destructor.

Algorithm
1.
2.
3.
4.
5.
6.
7.

Start
Declare class mystring with data member str and len
Define dynamic constructor using new operator
Define display function to print string contents
Define destructor that releases memory using delete operator
Create objects using constructor and invoke destructor when they go out of scope
Stop

Program
// 1c Destructor
#include <iostream.h>
#include <string.h>
class mystring
{
char *str;
int len;
public:
mystring (char *s)
// Dynamic constructor
{
len = strlen(s);
str = new char[len+1];
strcpy(str,s);
cout << "Dynamic memory allocation \n";
}
void display()
{
cout << str << "\n";
}
~mystring()
// Destructor
{
delete[] str;
cout << "Memory released \n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

int main()
{
mystring s1("SMKFIT");
s1.display();
}

Output
Dynamic memory allocation
SMKFIT
Memory released

Result
Thus memory allocated to objects were automatically released using destructor.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 2a

FRIEND FUNCTION

Aim
To access data members of a class using friend function.

Algorithm
1.
2.
3.
4.
5.
6.
7.

Start
Declare class sample with data members
Define a non-member function mean that returns aggregate of data members
Declare function mean as friend to class sample
Provide value for data members
Call function mean
Stop

Program
// 2a friend function
#include <iostream.h>
class sample
{
int a;
int b;
public:
void setvalue()
{
a = 25;
b = 40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/2;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

int main()
{
sample X;
X.setvalue();
cout << "Mean value = " << mean(X) ;
return 0;
}

Output
Mean value = 32.5

Result
Thus data members of a class were accessed by a non-member function using friend
keyword.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 2b

FRIEND CLASS

Aim
To demonstrate usage of friend classes

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare class rectangle with length and breadth as data members
Declare class square with side as data member
Declare class rectangle as friend to class square
Define function convert in rectangle class that takes square object as argument
Create objects for both classes
Call function convert to demonstrate friend class.
Stop

Program
// 2b Friend class
#include <iostream.h>
class square;
class rectangle
{
int width;
int height;
public:
int area ()
{
return (width * height);
}
void convert (square a);
};
class square
{
friend class rectangle;
int side;
public:
square (int a)
{
side = a;
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

10

void rectangle::convert(square a)
{
width = a.side;
height = a.side;
}
int main()
{
rectangle rect;
square sqr(4);
rect.convert(sqr);
cout << "Rectangle area : " << rect.area();
return 0;
}

Output
Rectangle area : 16

Result
Thus a class was declared as a friend to another class and its usage demonstrated.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 3a

11

SINGLE INHERITANCE

Aim
To demonstrate single inheritance using box class.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare class rectangle with protected members length and breadth
Define function rectdim to read values
Derive class box from rectangle in public mode with data member depth.
Define function getdata for box class that calls rectdim function
Create object for box class
Display volume of the box.
Stop

Program
//3a single inheritance
#include <iostream.h>
class rectangle
{
protected:
int length;
int breadth;
public:
void rectdim()
{
cout << "Enter length and breadth: ";
cin >> length >> breadth;
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

12

class box : public rectangle


{
protected:
int depth;
public:
void getdata()
{
rectdim();
cout << "Enter depth : ";
cin >> depth;
}
void display()
{
cout << "Box area : " << depth*length*breadth;
}
};
int main()
{
box b1;
b1.getdata();
b1.display();
return 0;
}

Output
Enter length and breadth : 4 5
Enter depth : 6
Box area : 120

Result
Thus single inheritance is demonstrated by having box class derived from rectangle.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 3b

13

HIERARCHICAL INHERITANCE

Aim
To illustrate hierarchical relationship for person details.

Algorithm
1. Start
2. Declare class person with protected members name, age and gender.
3. Define member function getperson and dispperson for person class.
4. Derive class student from person in public mode with members regno and course
5. Define member function getstudent and dispstudent for student class
6. Derive class staff from person in public mode with members qualfn and salary
7. Define member function getstaff and dispstaff for staff class.
8. Create objects for both student and staff class
9. Call functions belonging to person class as well as its own class for both objects.
10. Stop
Program
// 3b hierarchical inheritance
#include <iostream.h>
class person
{
protected:
char name[25];
int age;
char gender;
public:
void getperson()
{
cout << "General Details \n";
cout << "Enter name : ";
cin >> name ;
cout << "Enter age : ";
cin >> age;
cout << "Enter gender : ";
cin >> gender;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

14

void dispperson()
{
cout << "Name : " << name << "\n";
cout << "Gender : " << gender << "\n";
cout << "Age : " << age << "\n";
}
};
class student : public person
{
protected:
long regno;
char course[20];
public:
void getstudent()
{
cout << "Student Details \n";
cout << "Enter register no. : ";
cin >> regno ;
cout << "Enter course : ";
cin >> course;
}
void dispstudent()
{
cout << "\n" << "Register No. : " << regno << "\n"
<< "Course : " << course << "\n";
}
};
class staff : public person
{
protected:
char qualfn[20];
float salary;
public:
void getstaff()
{
cout << "Staff Details \n";
cout << " Enter degree : ";
cin >> qualfn;
cout << " Enter basic pay : ";
cin >> salary;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

15

void dispstaff()
{
cout << "Degree : " << qualfn << "\n";
cout << "Salary : " << salary << "\n";
}
};
int main()
{
student s1;
s1.getperson();
s1.getstudent();
s1.dispperson();
s1.dispstudent();
staff s2;
s2.getperson();
s2.getstaff();
s2.dispperson();
s2.dispstaff();
return 0;
}
Output
General Details
Enter name : gopal
Enter age : 20
Enter gender : M
Student Details
Enter register no. : 12345
Enter course : B.E(CSE)
Name : gopal
Gender : M
Age : 20
Register No. : 12345
Course : B.E(CSE)
General Details
Enter name : Suresh
Enter age : 35
Enter gender : M
Staff Details
Enter degree : M.Tech
Enter basic pay : 23456

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

16

Name : Suresh
Gender : M
Age : 35
Degree : M.Tech
Salary : 23456

Result
Thus student and staff class were derived from person class in a hierarchical manner.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 3c

17

MULTIPLE INHERITANCE

Aim
To calculate cut-off marks for engineering counseling using multiple inheritance.

Algorithm
1. Start
2. Declare class hslc with protected members math, phy and chem.
3. Define function getmarks to provide inputs for hslc class
4. Declare class entrance with protected member score
5. Define function getscore to provide inputs for entrance class.
6. Derive class result from classes hslc and entrance in public mode
7. Define function process that calls function getmarks and getscore
8. Define function display to print cut-off mark.
9. Create object for result class
10. Call process and display function
11. Stop
Program
// 3c multiple inheritance
#include <iostream.h>
class hslc
{
protected:
int math;
int phy;
int chem;
public:
void getmarks()
{
cout << "Enter maths, physics, chemistry marks : ";
cin >> math >> phy >> chem ;
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

18

class entrance
{
protected:
int score;
public:
void getscore()
{
cout << "Enter entrance score : ";
cin >> score;
}
};
class result : public hslc, public entrance
{
protected:
float cutoff;
public:
void process()
{
getmarks();
getscore();
cutoff=float(math/2+phy/4+chem/4+score);
}
void display()
{
cout << "Cut-off : " << cutoff;
}
};
int main()
{
result r1;
r1.process();
r1.display();
return 0;
}
Output
Enter maths, physics, chemistry marks : 134 156 145
Enter entrance score : 56
Cut-off : 198

Result
Thus result class exhibits multiple inheritance by inheriting members from hslc and
entrance class.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 3d

19

MULTILEVEL INHERITANCE

Aim
To demonstrate multilevel chain relationship amongst different classes.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare class vertebrate with function eat
Derive class mammal from vertebrate publicly with function suckle
Derive class primate from mammal publicly with function peel
Derive class human from primate publicly with function think
Create object for human class
Call derived functions eat, suckle and peel and its own function think
Stop

Program
// 3d multilevel inheritance
#include <iostream.h>
class vertebrate
{
public:
void eat()
{
cout << "Have spine and do eat \n";
}
};
class mammal : public vertebrate
{
public:
void suckle()
{
cout << "Feeded with milk \n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

20

class primate : public mammal


{
public:
void peel()
{
cout << "Can peel fruit \n";
}
};
class human : public primate
{
public:
void think()
{
cout << "Use my sixth sense \n";
}
};
int main()
{
human h1;
h1.eat();
h1.suckle();
h1.peel();
h1.think();
return 0;
}

Output
Have spine and do eat
Feeded with milk
Can peel fruit
Use my sixth sense

Result
Thus evolution of mankind from vertebrates is demonstrated using multilevel inheritance.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 3e

21

HYBRID INHERITANCE

Aim
To demonstrate hybrid inheritance using a combination of different types of inheritance.

Algorithm
1. Start
2. Declare class hslc with data members name and percent.
3. Define function gethslc and disphslc functions for hslc class
4. Derive class ug from hslc publicly with members course and cgpa
5. Define function getug and dispug for ug class
6. Declare class gate with data member score
7. Derive class pg from classes ug and gate publicly with member rank.
8. Define function getpg and disppg for pg class
9. Create object for pg class
10. Call all implementor functions
11. Call all accessor functions
12. Stop

Program
// 3e hybrid inheritance
#include <iostream.h>
class hslc
{
protected:
char name[20];
float percent;
public:
void gethslc()
{
cout << "Enter name and hslc percentage : ";
cin >> name >> percent;
}
void disphslc()
{
cout << "\n" << "Name : " << name << "\n";
cout << "Percentage : " << percent << "% \n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

22

class ug : public hslc


{
protected:
char course[20];
float cgpa;
public:
void getug()
{
cout << "Enter course and cgpa : ";
cin >> course >> cgpa;
}
void dispug()
{
cout << "Course " << course << "\n";
cout << "CGPA : " << cgpa << "\n";
}
};

class gate
{
protected:
float score;
public:
void getgate()
{
cout << "Enter gate score : ";
cin >> score;
}
void dispgate()
{
cout << "Gate score : " << score << "\n";
}
};
class pg : public ug, public gate
{
protected:
int rank;
public:
void getpg()
{
cout << "Enter rank : ";
cin >> rank;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

23

void disppg()
{
cout << "Rank : " << rank << "\n";
}
};
int main()
{
pg p1;
p1.gethslc();
p1.getug();
p1.getgate();
p1.getpg();
p1.disphslc();
p1.dispug();
p1.dispgate();
p1.disppg();
}

Output
Enter
Enter
Enter
Enter

name and hslc percentage : Gowtham 68


course and cgpa : B.E(CSE) 7.34
gate score : 44
rank : 6

Name : Gowtham
Percentage : 68%
Course B.E(CSE)
CGPA : 7.34
Gate score : 44
Rank : 6

Result
Thus admission process to pg courses was illustrated using hybrid inheritance.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 4a

24

FUNCTION OVERLOADING

Aim
To create a family of functions with same name to implement function polymorphism.

Algorithm
1. Start
2. Declare prototypes for function volume to compute volume of cube, box and
cylinder.
3. Define volume functions that varies on argument and implementation.
4. Call volume function with corresponding arguments
5. Stop
Program
// 4a function overloading
#include <iostream.h>
const float pi = 3.14;
int volume(int);
// cube volume
int volume(int, int, int);
// box volume
float volume(int, int);
// cylinder volume
int main()
{
cout << "Cube volume : " << volume(5) << "\n";
cout << "Box volume : " << volume(9, 3, 4) << "\n";
cout << "Cylinder volume : " << volume(5, 6) << "\n";
return 0;
}
int volume(int a)
{
return (a * a * a);
}
int volume(int l, int b, int h)
{
return (l * b * h);
}
Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

25

float volume(int r, int h)


{
return (pi * r * r * h);
}

Output
Cube volume : 125
Box volume : 108
Cylinder volume : 471

Result
Thus volume of cube, box and cylinder is accomplished using different version of volume
function.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 5a

26

VIRTUAL FUNCTION

Aim
To design a simple hierarchical classification for vehicle class and demonstrate runtime
polymorphism using virtual function.

Algorithm
1. Start
2. Declare class vehicle with protected members capacity, fuel, feature and virtual
function display
3. Derive class bicycle, autorickshaw and lorry from vehicle publicly.
4. Define default constructor for derived classes to initialize derived data members.
5. Redefine display function to print details for the corresponding vehicle
6. Create a vehicle class pointer and assign bicycle / autorickshaw / lorry object
7. Call display function to demonstrate runtime polymorphism
8. Stop

Program
// 5a virtual functions
#include <iostream.h>
#include <string.h>
class vehicle
{
protected:
int capacity;
char fuel[30];
char feature[100];
public:
virtual void display() { }
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

27

class bicycle : public vehicle


{
public:
bicycle()
{
capacity = 2;
strcpy(fuel, "Air");
strcpy(feature, "Green environment");
}
void display()
{
cout << "Bicycle \n";
cout << "Capacity : " << capacity << "\n";
cout << "Fuel : " << fuel << "\n";
cout << "Features : " << feature << "\n";
}
};
class autorikshaw : public vehicle
{
public:
autorikshaw()
{
capacity = 3;
strcpy(fuel, "Petrol/Diesel/LPG");
strcpy(feature, "Urban transport");
}
void display()
{
cout << "\n Autorickshaw \n";
cout << "Capacity : " << capacity << "\n";
cout << "Fuel : " << fuel << "\n";
cout << "Features : " << feature << "\n";
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

28

class lorry : public vehicle


{
public:
lorry()
{
capacity = 2;
strcpy(fuel, "Diesel");
strcpy(feature, "Cargo transport");
}
void display()
{
cout << "\n Lorry \n";
cout << "Capacity : " << capacity << "\n";
cout << "Fuel : " << fuel << "\n";
cout << "Features : " << feature << "\n";
}
};
int main()
{
vehicle *v1;
v1 = new bicycle;
v1->display();
v1 = new autorikshaw;
v1->display();
v1 = new lorry;
v1->display();
return 0;
}
Output
Bicycle
Capacity : 2
Fuel : Air
Features : Green environment
Autorickshaw
Capacity : 3
Fuel : Petrol/Diesel/LPG
Features : Urban transport

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

29

Lorry
Capacity : 2
Fuel : Diesel
Features : Cargo transport

Result
Thus dynamic or late binding is implemented by virtual function using hierarchical
inheritance of vehicle class.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 6a

30

UNARY OPERATOR OVERLOADING - MEMBER FUNCTION

Aim
To overload unary operator using member function.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.
9.

Start
Declare class space with data members x, y and z
Define parameterized constructor for space class
Define display function to print data members
Overload unary minus () using operator member function
Create a space object
Invoke unary minus on space object
Call display member function.
Stop

Program
// 6a unary operator using member function
#include <iostream.h>
class space
{
int x;
int y;
int z;
public:
space(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void display()
{
cout << x << " " << y << " " << z;
}
void operator-()
{
x = -x;
y = -y;
z = -z;
}
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

31

int main()
{
space S(1, 2, -3);
cout << "Original 3D coordinates : ";
S.display();
-S;
// operator invoked on class type
cout << "Negated 3D coordinates : ";
S.display();
return 0;
}

Output
Original 3D coordinates : 1 2 -3
Negated 3D coordinates : -1 -2 3

Result
Thus unary minus operator was overloaded using operator member function.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 6b

32

UNARY OPERATOR OVERLOADING - FRIEND FUNCTION

Aim
To overload unary operator ++ on fraction number using friend function.

Algorithm
1. Start
2. Declare class fraction with data members num and den
3. Define parameterized constructor for fraction class
4. Define display function to print data members
5. Declare operator function to overload ++ as friend to class fraction
6. Overload increment operator (++) as a non-member function
7. Create a fraction object
8. Invoke increment operator on fraction object
9. Call display member function.
10. Stop
Program
// 6b unary operator using friend function
#include <iostream.h>
class fraction
{
int num;
int den;
public:
fraction(int n, int d)
{
num = n;
den = d;
}
void display()
{
cout << num << "/" << den << "\n";
}
friend void operator ++(fraction &);
};
void operator ++(fraction &f)
{
f.num = f.num + f.den;
}
Vijai Anand

// overloading using friend

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

33

int main()
{
fraction f1(22,7);
cout << "Before increment : ";
f1.display();
++f1;
cout << "After increment : ";
f1.display();
}
Output
Before increment : 22/7
After increment : 29/7

Result
Thus pre increment operator ++ was overloaded as a friend function.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

34

Ex. 6c. BINARY OPERATOR OVERLOADING - MEMBER FUNCTION


Aim
To overload operator + to perform addition of two distance objects.

Algorithm
1.
2.
3.
4.
5.
6.
7.

Start
Declare class distance with data members inch and feet
Define default and parameterized constructor for distance class
Define display function to print data members
Overload operator + using operator member function
Create two distance object with input values.
Sum the distance objects using overloaded + and store result in another distance
object
8. Call display member function.
9. Stop
Program
// 6c binary operator using member function
#include <iostream.h>
class distance
{
int feet;
int inch;
public:
distance()
{
feet = inches = 0;
}
distance(int f, int i)
{
feet = f;
inch = i;
}
void display()
{
cout << feet << "." << inch << "ft \n";
}
distance operator +(distance); //addition (+) overloaded
bool operator <(distance);
//less than(<) overloaded
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

35

distance distance::operator +(distance d2)


{
int f = feet + d2.feet;
int i = inch + d2.inch;
if(i >= 12.0)
// 12 inch = 1 feet
{
i = i - 12;
f++;
}
return distance(f, i);
}
bool distance::operator <(distance d2)
{
float f1 = feet + float(inch)/12;
float f2 = d2.feet + float(d2.inch)/12;
return (f1 < f2) ? true : false;
}
int main()
{
distance d1(10, 6), d2(11, 6), d3;
cout << "Distance1 : ";
d1.display();
cout << "Distance2 : ";
d2.display();
d3 = d1 + d2;
cout << "Distance3 : ";
d3.display();
if (d1 < d2)
cout << "Distance1 is nearest";
else
cout << "Distance2 is nearest";
return 0;
}
Output
Distance1
Distance2
Distance3
Distance1

: 10.6ft
: 11.6ft
: 22.0ft
is nearest

Result
Thus two distance objects were added using operator overloading.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 6d

36

BINARY OPERATOR OVERLOADING FRIEND FUNCTION

Aim
To create an array1d class and to overload operators + and to perform addition and
subtraction of one dimensional array.

Algorithm
1.
2.
3.
4.
5.
6.

Start
Declare class array1d with data members arr containing an array
Define getdata function to obtain input for array elements
Define display function to print array elements
Declare overloading of operator + and as friend to class array1d
Overload operator + as a non-member function to perform scalar addition on array
elements
7. Overload operator as a non-member function to perform array subtraction
8. Create array1d objects.
9. Call getdata function for each object
10. Invoke the overloaded operator + and on array1d objects
11. Call display member function.
12. Stop

Program
// 6d binary operator using friend function
#include <iostream.h>
const int size = 5;
class array1d
{
int arr[size];
public:
void getdata()
{
for (int i=0; i<size; i++)
cin >> arr[i];
}
void display()
{
for(int i=0; i<size; i++)
cout << arr[i] << " ";
}
friend array1d operator + (int, array1d);
friend array1d operator - (array1d, array1d);
};

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

37

array1d operator +(int x, array1d v)


{
array1d tmp;
for (int i=0; i<size; i++)
tmp.arr[i] = x + v.arr[i];
return tmp;
}
array1d operator -(array1d v1, array1d v2)
{
array1d tmp;
for (int i=0; i<size; i++)
tmp.arr[i] = v1.arr[i] - v2.arr[i];
return tmp;
}
int main()
{
array1d B, C, K,
cout << "Enter 5
B.getdata();
C = 2 + B;
cout << "2 + B =
C.display();
cout << "\nEnter
S.getdata();
cout << "Enter 5
T.getdata();
K = S - T;
cout << "S - T =
K.display();
return 0;
}

S, T;
elements for B array

: ";

";
5 elements for S array
elements for T array

: ";
: ";

";

Output
Enter
2 + B
Enter
Enter
S - T

5
=
5
5
=

elements for B array


3 4 5 6 7
elements for S array
elements for T array
-2 2 5 6 2

: 1 2 3 4 5
: 0 9 8 7 6
: 2 7 3 1 4

Result
Thus one-dimensional array scalar addition and subtraction was performed using operator
overloading as a friend function.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 7a

38

FUNCTION TEMPLATES

Aim
To perform bubble sort on an array using function templates.

Algorithm
1. Start
2. Define function template arrange to implement bubble sort with array argument
of template type
3. Declare different types of array containing unordered elements
4. Call arrange function for each array
5. Display array elements for each array
6. Stop

Program
// 7a function templates
#include <iostream.h>
template <class T>
// Template function
void arrange(T arr[], int size)
{
for(int i=0; i<size-1; i++)
{
for(int j=i+1; j<size; j++)
{
if (arr[i] > arr[j])
{
T temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

39

int main()
{
int x[6] = {1, -4, 8, 0, 3, 5};
float y[6] = {2.2, -0.4, 3.5, 1.9, 2.7, 0.7};
char z[7] = {'I', 'n', 'd', 'i', 'a', 'n'};
arrange(x,6);
arrange(y,6);
arrange(z,6);
cout << "Sorted Arrays \n Int \t Float \t Char \n";
for (int i=0; i<6; i++)
cout << x[i] << "\t" << y[i] << "\t" << z[i] << "\n";
return 0;
}

Output
Sorted Arrays
Int
Float
-4
-0.4
0
0.7
1
1.9
3
2.2
5
2.7
8
3.5

Char
I
a
d
i
n
n

Result
Thus arrays of different types were sorted using a templated bubble sort routine.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 7b

40

CLASS TEMPLATES

Aim
To implement stack operations push and pop using class template.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Declare a template class mystack with array data member st of template type
Define a default constructor that initializes top data member
Define push and pop operation with template arguments
Define function full and empty to indicate stack full or empty
Create mystack objects of different types.
Invoke stack operations for each mystack object
Stop

Program
// 7b class template
#include <iostream.h>
const int size = 5;
template <class T>
class mystack
{
T st[size];
int top;
public:
mystack()
{
top = -1;
}
void push(T var)
{
st[++top] = var;
}
T pop()
{
return st[top--];
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

41

bool empty()
{
if (top < 0)
return true;
else
return false;
}
bool full()
{
if (top == size-1)
return true;
else
return false;
}
};
int main()
{
mystack <char>
mystack <int>

s1; // Character Stack


s2; // Integer stack

for (char x='a'; x<='e'; x++)


{
if (s1.full())
cout << "Char Stack Full";
else
s1.push(x);
}
cout << "Character Stack Pop : ";
while (!s1.empty())
cout << s1.pop();
for (int i=5; i<10; i++)
{
if (S2.isFull())
cout << "\n\nInt Stack Overflow";
else
S2.Push(i);
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

42

cout << "\nInteger Stack Pop : ";


while (!s2.empty())
cout << s2.pop();
return 0;
}
Output
Character Stack Pop : e d c b a
Integer Stack Pop : 9 8 7 6 5

Result
Thus stack operations push and pop were demonstrated on stack of different data types.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 8a

43

EXCEPTION HANDLING

Aim
To demonstrate exception handling in C++ using try, throw and catch mechanism.

Algorithm
1.
2.
3.
4.
5.
6.

Start
Read two numbers a and b
Within try block, if b = 0 then raise exception for b
Otherwise execute arithmetic expression a / b
Define catch block to handle divide by zero exception
Stop

Program
// 8a Exception handling
#include <iostream.h>
int main()
{
int a, b, x;
cout << "Enter values for A and B : ";
cin >> a >> b;
try
{
if (b == 0)
throw(b);
else
cout << float(a)/b;
}
catch(int i)
{
cout << "Divide by zero error for A/B";
}
return 0;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

44

Output
Enter values for A and B : 3 0
Divide by zero error for A/B

Result
Thus divide-by-zero error is handled using try, throw and catch mechanism.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 8b

45

EXCEPTION HANDLING CLASSES

Aim
To implement stack operations using exception handling mechanism.

Algorithm
1. Start
2. Declare mystack class with data members top and array st
3. Define exception classes full and empty for mystack class
4. Define push operation for mystack class. If stack is full then throw full exception
5. Define pop operation. If stack has no elements then throw empty exception
6. Create mystack object.
7. Perform a series of push and pop operation within try block.
8. On stack overflow and underflow raise full and empty exception.
9. Define catch handlers for full and empty type exceptions
10. Stop
Program
// 8b Exception using classes
#include <iostream.h>
const int size = 3;
class mystack
{
int st[size];
int top;
public:
class full { };
class empty { };
mystack()
{
top = -1;
}
void push(int var)
{
if(top >= size-1)
throw full();
full
st[++top] = var;
}

Vijai Anand

//exception class
//exception class

//throw exception for stack

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

int pop()
{
if(top < 0)
throw empty();
empty
return st[top--];
}

46

//throw exception for stack

};
int main()
{
mystack s1;
try
{
s1.push(11);
s1.push(22);
s1.push(33);
cout << "Poping stack \n";
cout << s1.pop() << "\n";
cout << s1.pop() << "\n";
cout << s1.pop() << "\n";
cout << s1.pop();
// stack empty error
}
catch(mystack::full)
{
cout << Exception: Stack Full;
}
catch(mystack::empty)
{
cout << Exception: Stack Empty;
}
catch(...) { }
// generic catch
return 0;
}
Output
Poping stack
33
22
11
Exception: Stack Empty

Result
Thus push and pop operations of a stack was demonstrated using exception handling.
Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 9a

47

C++ STRING CLASS

Aim
To demonstrate functionality of C++ string class.

Algorithm
1.
2.
3.
4.
5.
6.

Start
Include header file string
Create objects of string class
Call member functions insert, append, erase, replace, swap, etc on string objects
Display the resultant string after each function call.
Stop

Program
// 9a STL string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("ANSI "),s2("Standard "),s3,s4;
cout << "Enter string s3 : ";
cin >> s3;
s4 = s3;
if (s3 == s4)
cout << "Strings s3 and s4 are identical \n";
s4 = s1 + s2 + s3;
cout << "s1 + s2 + s3 = " << s4 << "\n";
string s5 = "ISO ";
cout << "s5 inserted in s2 : " << s2.insert(0,s5) << "\n";
cout << "s3 appended to s2 : " << s2.append(s3) << "\n";
cout << "s4 after deletion : " << s4.erase(7,3) << "\n";
cout << "Replace in s2 : " << s2.replace(0,4,s1) << "\n";
s1.swap(s3);
cout << "Swap : s1 = " << s1 << " s3 = " << s3 << "\n";
cout << "Substring in s2 : " << s2.substr(7,3) << "\n";
cout << "a occurs at : " << s2.find_first_of('a') << "\n";
for(int i=0; i<s2.length(); i++)
cout << s2[i];
return 0;
}
Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

48

Output
Enter string s3 : C++
Strings s3 and s4 are identical
s1 + s2 + s3 = ANSI Standard C++
s5 inserted in s2 : ISO Standard
s3 appended to s2 : ISO Standard C++
s4 after deletion : ANSI Stard C++
Replace in s2 : ANSI Standard C++
Swap : s1 = C++ s3 = ANSI
Substring in s2 : and
a occurs at : 7
ANSI Standard C++

Result
Thus strings were manipulated using various member functions of C++ string class
successfully.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 9b

49

STL VECTOR

Aim
To demonstrate the functionality of sequence container STL vector class.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.
9.

Start
Include header file vector
Create a vector object v1 to store integers.
Use push_back member function to append elements onto v1
Delete last element in v1 using pop_back member function
Display first and last element of v1 using front and back member function
Display length of v1 using size member function
Display v1 elements using a loop
Stop

Program
// 9b STL vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v1(5);
int data, i;

// Vector of size 5

cout << "Enter 5 vector elements : ";


for (i=0; i<v1.size(); i++)
cin >> v1[i];
cout << "Enter element to append : ";
cin >> data;
v1.push_back(data);
// Add element dynamically
cout << "Current size: " << v1.size() << "\n";
cout << "First element : " << v1.front() << "\n";
cout << "Last element : " << v1.back() << "\n";

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

50

if (!v1.empty())
v1.pop_back();
// Deleting last element
cout << "Size after pop : " << v1.size() << "\n";
cout << "Vector elements : ";
for (i=0; i<v1.size(); i++)
cout << v1[i] << " ";
return 0;
}

Output
Enter 5 vector elements : 9 3 6 1 5
Enter element to append : 2
Current size: 6
First element : 9
Last element : 2
Size after pop : 5
Vector elements : 9 3 6 1 5

Result
Thus a dynamic array with random access is implemented using STL vector.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 9c

51

STL LIST

Aim
To demonstrate functionality of bidirectional sequence container STL List class.

Algorithm
1. Start
2. Include header file list
3. Create list objects l2, l3 to store integers.
4. Declare an iterator first to step through list elements.
5. Insert odd numbers onto l2 from 1 to 10 using push_back member function
6. Insert even numbers onto l2 from 1 to 10 using push_front member function
7. Assign first to point to first element of a list using begin member function
8. Print list l2 and l3 elements using a loop
9. Sort list l3 using sort member function
10. Merge list l3 with l2 using merge member function
11. Print list l2 elements using a loop
12. Stop
Program
// 9c STL List
#include <iostream>
#include <list>
using namespace std;
int main()
{
list <int> l2,l3;
list <int>::iterator first;
for (int i=1; i<10; i+=2)
l2.push_back(i);
for (int i=2; i<10; i+=2)
l3.push_front(i);
first = l2.begin();
cout << "List L2 : ";
while (first != l2.end())
cout << *first++ << " ";

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

52

first = l3.begin();
cout << "List L3 : ";
while (first != l3.end())
cout << *first++ << " ";
l3.sort();
l2.merge(l3);
cout << "\n Merged List " ;
first = l2.begin();
while(first != l2.end())
cout << *first++ << " ";
return 0;
}

Output
List L2 : 1 3 5 7 9
List L3 : 8 6 4 2
Merged List 1 2 3 4 5 6 7 8 9

Result
Thus various operations are performed on STL list using its member function.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 9d

53

STL MAPS

Aim
To demonstrate search operation on associative container STL map.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.
9.

Start
Include header file map
Create map object m1 to store character and its corresponding ASCII value
Declare an iterator ptr to step through map elements.
Populate map m1 using insert with pair member function
Read a character ch from the user
Search map m1 for the given key ch using find member function
If found then display corresponding ASCII value using member second
Stop

Program
// 9d STL Maps
#include <iostream>
#include <map>
using namespace std;
int main()
{
map <char, int> m1;
map <char, int>::iterator ptr;
char ch;
for(int i=0; i<26; i++)
m1.insert(pair<char, int>('A'+i, 65+i));
cout << "Enter key: ";
cin >> ch;
ptr = m1.find(ch);
if(ptr != m1.end())
cout << "ASCII value : " << ptr->second;
else
cout << "Key not in map";

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

54

return 0;
}

Output
Enter key: P
ASCII value : 80

Result
Thus elements were inserted into a STL map and value retrieved for the given key.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 9e

55

STL ALGORITHM

Aim
To sort the given array using STL algorithms in descending order.

Algorithm
1.
2.
3.
4.
5.
6.

Start
Include header file algorithm and functional
Initialize a float array fdata with 5 elements
Sort the array using sort function with greater predicate
Print fdata elements using a loop
Stop

Program
// 9e STL function objects
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
float fdata[] = { 19.2, 87.4, -33.6, 55.0, 42.2 };
sort(fdata, fdata+5, greater<float>());
// sort array
cout << "Sorted array : ";
for(int j=0; j<5; j++)
cout << fdata[j] << " " ;
return 0;
}
Output
Sorted array : 87.4 55 42.2 19.2 -33.6

Result
Thus the given array is sorted using STL algorithms and function objects.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 10a

56

CHARACTER FILE I/O

Aim
To write characters onto a file and to find number of vowels in it using character file
input/output operations.

Algorithm
1. Start
2. Include header file fstream
3. Declare a file object fp
4. Open file sample.txt in output mode using open function
5. Fetch character-by-character from console using get function
6. Write it onto file using put function,
7. Repeat steps 5-6 until end-of-file is encountered.
8. Close the file object fp using close function
9. Open file sample.txt in input mode using open function
10. Initialize vc to 0.
11. Read character-by-character from file using get function
12. If character is a vowel, then increment vc.
13. Repeat steps 11-12 until end-of-file is encountered
14. Print vc
15. Close the file object fp using close function
16. Stop
Program
// 10a character file operations
#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
int main()
{
fstream fp;
char ch;
fp.open("sample.txt", ios::out);
cout << "Ctrl + Z to terminate: \n";
while( (ch = cin.get()) != EOF)
fp.put(ch);
fp.close();

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

57

int vc = 0;
fp.open("sample.txt", ios::in);
while(fp)
{
ch = fp.get();
switch(tolower(ch))
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
vc++;
break;
}
}
cout << "No. of vowels : " << vc;
fp.close();
return 0;
}

Output
Ctrl + Z to terminate:
how are you
i am fine
bye
^Z
No. of vowels : 10

Result
Thus a file was created and analyzed using get and put file I/O methods.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 10b

58

FILE COPY

Aim
To copy an entire file using characteroriented file I/O with exception handling.

Algorithm
1. Start
2. Include header file fstream
3. Declare ifstream object src and ofstream object dst
4. Get source and destination filenames from user.
5. Within try block, open source file using src.
6. Open destination file using dst
7. If source file non-existent then raise an exception using throw
8. Read a character from source file using get function
9. Write that character onto destination file using put function
10. Repeat steps 8-9 until end-of-file is encountered
11. Define catch block to handle file-not-found exception
12. Stop
Program
// 10b File copy
#include <fstream.h>
#include <iostream.h>
int main()
{
ifstream src;
ofstream dst;
char file1[10], file2[10];
char ch;
cout << "Enter source and destination file : ";
cin >> file1 >> file2;
try
{
src.open(file1);
if(src.fail())
throw file1;
// Source file non-existent
dst.open(file2);

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

59

while(src)
{
ch = src.get();
dst.put(ch);
}
cout << "File copied";
src.close();
dst.close();
}
catch (char *name)
{
cout << "Source file not available";
}
return 0;
}

Output
Enter source and destination file : hello.c
File copied

filecopy.c

Result
Thus file is copied using character I/O with exception handling mechanisms.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 10c

60

BINARY FILE I/O SEQUENTIAL ACCESS

Aim
To write product details as a binary file and to access product records sequentially.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Include header file fstream
Declare class product with data members code, name and rate.
Define member function getdata, putdata and prodcode for product class
Create object for fstream and product class as fobj and p1 respectively
Display file operations as menu
Accept choice
If choice = 1 then
a. Open file invent.dat in append mode using open function
b. Obtain product details p1 using getdata member function
c. Write p1 onto file in binary format using write function
d. Close the file object fobj using close function
9. If choice = 2 then
a. Open file invent.dat in read mode
b. Accept product code pcode to be searched
c. Fetch a product record from file onto p1 using read function
d. Obtain code from p1 using prodcode member function
e. If p1's code = pcode then print product details using putdata member function
f. Repeat steps c e until end-of-file is reached
g. Close the file object fobj using close function
10. Stop
Program
// 10c Objects with sequential access
#include <fstream.h>
#include <iostream.h>
class product
{
int code;
char name[20];
float rate;

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

61

public:
void getdata()
{
cout << "Enter product code, name, rate : ";
cin >> code >> name >> rate;
}
void putdata()
{
cout << "Name : " << name << "\n";
cout << "Rate : " << rate << "\n";
}
int prodcode()
{
return code;
}
};
int main()
{
fstream fobj;
product p1;
int ch, pid;
cout << "1.Append 2.Display \n";
cout << "Enter your choice : ";
cin >> ch;
switch(ch)
{
case 1:
p1.getdata();
fobj.open("invent.dat",
fobj.write((char *)&p1,
fobj.close();
break;
case 2:
cout << " Enter product
cin >> pid;
fobj.open("invent.dat",

Vijai Anand

ios::app|ios::binary);
sizeof(p1));

code : ";
ios::in );

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

62

while (fobj.read((char *)&p1, sizeof(p1)))


{
if (pid == p1.prodcode())
{
p1.putdata();
break;
}
}
fobj.close();
break;
}
return 0;
}

Output
1.Append 2.Display
Enter your choice : 1
Enter product code, name, rate : 12 hamam 35.75
1.Append 2.Display
Enter your choice : 1
Enter product code, name, rate : 10 Dettol 109.5
1.Append 2.Display
Enter your choice : 2
Enter product code : 12
Name : hamam
Rate : 35.75

Result
Thus product details were appended to a file and accessed in a sequential manner.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 10d

63

BINARY FILE I/O RANDOM ACCESS

Aim
To write student details as a binary file and to access student records randomly.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Include header file fstream
Declare class student with data members rollno, name, arrears and cgpa
Define member function getdata and display for student class
Create object for fstream and student class as fobj and s1 respectively
Display file operations as menu
Accept choice
If choice = 1 then
a. Open file placement.dat in append mode using open function
b. Obtain student details s1 using getdata member function
c. Write s1 onto file in binary format using write function
d. Close the file object fobj using close function
9. If choice = 2 then
a. Open file invent.dat in read mode
b. Accept roll number rno to be searched
c. Move file pointer to desired student record using seekg function
d. Fetch student record from file onto s1 using read function
e. Print s1 student details using display member function
f. Close the file object fobj using close function
10. Stop
Program
// 10d Object using random access
#include <fstream.h>
#include <iostream.h>
class student
{
int rollno;
char name[20];
int arrear;
float cgpa;

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

64

public:
void getdata()
{
cout << "Enter rollno, name, arrear, cgpa : ";
cin >> rollno >> name >> arrear >> cgpa;
}
void display()
{
cout << "Name : " << name << "\n";
cout << "Arrears : " << arrear << "\n";
cout << "CGPA : " << cgpa << "\n";
}
};
int main()
{
fstream fobj;
student s1;
int ch, rno;
cout << "1.Append 2.Display";
cout << "\nEnter your choice : ";
cin >> ch;
switch(ch)
{
case 1:
s1.getdata();
fobj.open("placement.dat", ios::app|ios::binary);
fobj.write((char *)&s1, sizeof(s1));
fobj.close();
break;
case 2:
fobj.open("placement.dat", ios::in|ios::binary);
cout << "Enter roll number : ";
cin >> rno;
fobj.seekg((rno - 1) * sizeof(s1), ios::beg);
fobj.read((char *)&s1, sizeof(s1));
s1.display();
fobj.close();
break;
}
return 0;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

65

Output
1.Append 2.Display
Enter your choice : 1
Enter rollno, name, arrear, cgpa : 1 vijai 6 6.2
1.Append 2.Display
Enter your choice : 1
Enter rollno, name, arrear, cgpa : 2 anand 0 7.08
1.Append 2.Display
Enter your choice : 2
Enter roll number : 1
Name : vijai
Arrears : 6
CGPA : 6.2

Result
Thus student details was appended to a file and retrieved randomly.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 11a

66

TOWERS OF HANOI

Aim
To solve Towers of Hanoi problem using stack operations.

Algorithm
1.
2.
3.
4.
5.
6.
7.
8.

Start
Get number of disks, say n.
Push parameters and return address onto stack
If the stopping value has been reached then pop the stack to return to previous level
else move all except the final disc from starting to intermediate needle.
Move final discs from start to destination needle.
Move remaining discs from intermediate to destination needle.
Return to previous level by popping stack.
Stop

Program
// 11a Stack appln: towers of Hanoi
#include <iostream.h>
void tower(int a,char from,char aux,char to)
{
if(a == 1)
{
cout << "Move disc 1 from " << from;
cout << " to " << to << "\n";
return;
}
else
{
tower(a-1, from, to, aux);
cout << "Move disc " << a << " from " << from;
cout << " to " << to <<"\n";
tower(a-1, aux, from, to);
}
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

67

int main()
{
int n;
cout << "Tower of Hanoi \n";
cout << "Enter number of discs : ";
cin >> n;
tower(n, 'A','B','C');
return 0;
}

Output
Tower of Hanoi
Enter number of discs
Move disc 1 from A to
Move disc 2 from A to
Move disc 1 from B to

: 2
B
C
C

Result
Thus n disks of different sizes are moved from rod A to rod C in an orderly manner.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 12/13a

68

BINARY SEARCH TREE TRAVERSAL

Aim
To create a binary search tree and to perform different methods of tree traversal.

Algorithm
1. Start
2. Declare structure node to store element, left child and right child for a binary search
tree
3. Declare class bst with member functions insert, preorder, inorder and postorder
4. Define insert member function to add an element
a. If first element, then place it as root
b. If element < root then traverse left subtree recursively until leaf
c. If element > root then traverse right subtree recursively until leaf
d. Insert new element as leaf
5. Define preorder member function to perform preorder traversal recursively
a. Visit root node
b. Visit left subtree
c. Visit right subtree
6. Define inorder member function to perform inorder traversal recursively
a. Visit left subtree
b. Visit root node
c. Visit right subtree
7. Define postorder member function to perform postorder traversal recursively
a. Visit left subtree
b. Visit right subtree
c. Visit root node
8. Create object tree for bst class
9. Display a choice menu in main function
10. Accept choice and invoke appropriate member function for tree object
11. Stop

Program
// 12a binary search tree and traversal
#include<iostream.h>
#include <process.h>
#include<stdlib.h>
#include <malloc.h>

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

69

struct node
{
int element;
node *left;
node *right;
};
typedef struct node *pnode;
class bst
{
public:
void insert(int, pnode &);
void preorder(pnode);
void inorder(pnode);
void postorder(pnode);
};
void bst::insert(int new_element, pnode& root)
{
if (root == NULL)
{
root = new node;
root->element = new_element;
root->left = NULL;
root->right = NULL;
}
else
{
if (new_element < root->element)
insert (new_element, root->left);
else
if (new_element > root->element)
insert (new_element, root->right);
else
cout << "element already Exits !";
}
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

70

void bst::preorder(pnode root)


{
if (root != NULL)
{
cout << root->element << "-->";
preorder (root->left);
preorder (root->right);
}
}
void bst::inorder(pnode root)
{
if (root != NULL)
{
inorder (root->left);
cout << root->element << "-->";
inorder (root->right);
}
}
void bst::postorder(pnode root)
{
if (root != NULL)
{
postorder (root->left);
postorder (root->right);
cout << root->element << "-->";
}
}
int main()
{
int choice, element, left_child , right_child;
bst tree;
char c = 'y';
pnode root, min, max;
root = NULL;

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

71

while(1)
{
cout << "\n Binary Search Tree \n";
cout << "1.insert 2.preorder 3.inorder 4.postorder";
cout << " 0.Exit \n Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the new element : ";
cin >> element;
tree.insert (element, root);
cout << "Inorder traversal is : ";
tree.inorder(root);
break;
case 2:
if (root == NULL)
cout << " Tree is empty";
else
{
cout << "Preorder traversal is : ";
tree.preorder(root);
}
break;
case 3:
if (root == NULL)
cout << " Tree is empty";
else
{
cout << "Inorder traversal is : ";
tree.inorder(root);
}
break;
case 4:
if (root == NULL)
cout << "Tree is empty";
else

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

72

{
cout << "Postorder traversal is : ";
tree.postorder(root);
}
break;
case 0:
exit (0);
}
}
return 0;
}
Output
Binary Search Tree
1.insert 2.preorder 3.inorder 4.postorder
Enter your choice : 1
Enter the new element : 5
Inorder traversal is : 5-->
Binary Search Tree
1.insert 2.preorder 3.inorder 4.postorder
Enter your choice : 1
Enter the new element : 7
Inorder traversal is : 5-->7-->
Binary Search Tree
1.insert 2.preorder 3.inorder 4.postorder
Enter your choice : 1
Enter the new element : 3
Inorder traversal is : 3-->5-->7-->
Binary Search Tree
1.insert 2.preorder 3.inorder 4.postorder
Enter your choice : 2
Preorder traversal is : 5-->3-->7-->

0.Exit

0.Exit

0.Exit

0.Exit

Result
Thus elements were inserted onto an empty binary search tree and traversed in different
ways.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 14a

73

PRIM'S MINIMUM SPANNING TREE

Aim
To determine edges for minimum spanning tree in the given graph using Prim's algorithm

Algorithm
1.
2.
3.
4.

Start
Define infinity to be a large number, say 999.
Declare class prim with requisite data members
Define create member function
a. Get number of vertices nodes.
b. Read adjacency matrix graph using a loop
c. For nodes with cost 0, assign infinity using a loop
5. Define findmst member function to determine minimum spanning tree
a. Initially all nodes are unselected
b. Find smallest edge from the graph connecting the vertex
c. Add that vertex
d. Print associated cost
e. Repeat the process until all vertices are added
f. Print total cost of Prim's MST
6. Create object pmst for prim class
a. Call create member function
b. Call findmst member function
7. Stop
Program
// 14a Prims MST
#include <iostream.h>
#define
#define
#define
#define
#define

row 10
col 10
infi 999
false 0
true 1

class prims
{
int graph[row][col];
int nodes;

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

74

public:
prims()
{
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
graph[i][j]=0;
}
void create();
void findmst();
};
void prims::create()
{
int i,j;
cout << "Enter Total Nodes : ";
cin >> nodes;
cout << "Enter Adjacency Matrix : \n";
for(i=0; i<nodes; i++)
for(j=0; j<nodes; j++)
cin >> graph[i][j];
for(i=0; i<nodes; i++)
for(j=0; j<nodes; j++)
if(graph[i][j] == 0)
graph[i][j] = infi;
}
void prims::findmst()
{
int selected[row],i,j,ne;
int min,x,y,cost=0;
for(i=0; i<nodes; i++)
selected[i] = false;
selected[0] = true;
ne = 0;

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

75

while(ne < nodes-1)


{
min = infi;
for(i=0; i<nodes; i++)
{
if(selected[i] == true)
{
for(j=0; j<nodes; j++)
{
if(selected[j] == false)
{
if(min > graph[i][j])
{
min = graph[i][j];
x = i;
y = j;
}
}
}
}
}
selected[y] = true;
cout << x+1 << " -> " << y+1 << " = " << graph[x][y] <<
"\n";
cost += graph[x][y];
ne = ne + 1;
}
cout << "Cost of MST is : " << cost;
}

int main()
{
prims pmst;
cout << "Prims Algorithm \n";
pmst.create();
cout << "Edges of Minimum Spanning Tree are : \n";
pmst.findmst();
return 0;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

76

Output
Prims Algorithm
Enter Total Nodes : 7
Enter Adjacency Matrix :
0 2 4 1 0 0 0
2 0 0 3 9 0 0
4 0 0 2 0 5 0
1 3 2 0 7 8 4
0 9 0 7 0 0 6
0 0 5 8 0 0 1
0 0 0 4 6 1 0
Edges of Minimum Spanning Tree are :
1 -> 4 = 1
1 -> 2 = 2
4 -> 3 = 2
4 -> 7 = 4
7 -> 6 = 1
7 -> 5 = 6
Cost of MST is : 16

Result
Thus minimum spanning tree for the given graph is determined using Prim's algorithm.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 14b

77

KRUSKA'S MINIMUM SPANNING TREE

Aim
To determine minimum spanning tree for the given graph using Kruskal's algorithm

Algorithm
1. Start
2. Declare class kruskal with requisite data members
3. Define read member function
a. Get the number of vertices nodes
b. Read adjacency matrix cost using a loop
c. Update cost of an edge to 999 if it's 0 using a loop
d. Call kmst member function
4. Define kmst member function to determine minimum spanning tree
a. Find edge with minimum cost
b. Add edge if it does not form a cycle
c. Print cost of the edge
d. Repeat until all vertices are included
e. Print cost of minimum spanning tree
5. Create object k1 for kurskal class
a. Call read member function
6. Stop
Program
// 14b Kruskal's Algorithm
#include<iostream.h>
#include<conio.h>
int parent[10];
class kruskal
{
int node1, node2, unvisited, visited, i, j, nodes, edges;
int minvalue, mincost, cost[10][10];

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

78

public:
kruskal()
{
edges = 1;
mincost = 0;
}
void read();
void kmst(int cost[][10], int n);
};
void kruskal::read()
{
cout << "Enter No. of vertex : ";
cin >> nodes;
cout << "Enter adjacency matrix(cost) : \n";
for (i=1; i<=nodes; i++)
{
for(j=1; j<=nodes; j++)
{
cin >> cost[i][j];
if (cost[i][j] == 0)
cost[i][j] = 999;
}
}
kmst(cost, nodes);
}

void kruskal::kmst(int cost[][10], int n)


{
cout << "Minimum cost edges are : \n";
while ( edges < n )
{
minvalue = 999;
for (i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
if(cost[i][j] < minvalue)
{
minvalue = cost[i][j];

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

79

node1 = unvisited = i;
node2 = visited = j;
}
}
}
while(parent[unvisited])
unvisited = parent[unvisited];
while(parent[visited])
visited = parent[visited];
if(unvisited != visited)
{
edges++;
cout << "edge(" << node1 << "->" << node2 << ") = "
<< minvalue << "\n";
mincost += minvalue;
parent[visited] = unvisited;
}
cost[node1][node2] = cost[node2][node1] = 999;
}
cout << "MST cost = " << mincost;
}
int main()
{
kruskal k1;
k1.read();
return 0;
}

Output
Enter
Enter
0 2 4
2 0 0
4 0 0
1 3 2
0 9 0
0 0 5
0 0 0

No. of vertex : 7
adjacency matrix(cost):
1 0 0 0
3 9 0 0
2 0 5 0
0 7 8 4
7 0 0 6
8 0 0 1
4 6 1 0

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

80

Minimum cost edges are:


edge(1->4) = 1
edge(6->7) = 1
edge(1->2) = 2
edge(3->4) = 2
edge(4->7) = 4
edge(5->7) = 6
MST cost = 16

Result
Thus minimum spanning tree for the given graph is determined using Kruskal's
algorithm.

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

Ex. 15a

81

DIJKSTRA SHORTEST PATH

Aim
To find shortest path from a given vertex to all other vertices using Dijkstra algorithm

Algorithm
1.
2.
3.
4.

Start
Define infinity to be a large number, say 999.
Declare class dijkstra with requisite data members
Define read member function to obtain inputs
a. Get the number of vertex vertices
b. Read adjacency matrix adj using a loop
c. Get vertex to start with source.
5. Define initialize member function to do initial configuration
a. Initialize distance for each vertex to infinity
b. Initialize all nodes marked as false
c. Initialize all nodes as without any predecessor
6. Define unmarked member function
a. Return vertex with minimum distance amongst unmarked vertices
7. Define calculate member function
a. Call initialize member function
b. Update variables marked, distance and predecessor for adjacent vertices
8. Define path member function to print path recursively
9. Define output member function
a. Call path member function to print path from source to each other vertex
b. Print total distance from source to that vertex
10. Create object djk for dijkstra class
a. Call read member function
b. Call calculate member function
c. Call output member function
11. Stop
Program
// 15a Dijkstra's shortest path algorithm
#include<iostream.h>
#define infinity 999

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

82

class dijkstra
{
int adj[15][15];
int predecessor[15];
int distance[15];
bool mark[15];
int source;
int vertices;
public:
void read();
void initialize();
int unmarked();
void calculate();
void output();
void path(int);
};
void dijkstra::read()
{
cout << "Enter number of vertices : ";
cin >> vertices;
cout << "Enter adjacency matrix for the graph : \n";
cout << "(For infinity enter " << infinity << ")\n";
for(int i=0; i<vertices; i++)
for(int j=0; j<vertices; j++)
cin >> adj[i][j];
cout << "Enter the source vertex : ";
cin >> source;
}
void dijkstra::initialize()
{
for(int i=0; i<vertices; i++)
{
mark[i] = false;
predecessor[i] = -1;
distance[i] = infinity;
}
distance[source] = 0;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

83

int dijkstra::unmarked()
{
int min = infinity;
int closest;
for(int i=0; i<vertices; i++)
{
if((!mark[i]) && ( min >= distance[i]))
{
min = distance[i];
closest = i;
}
}
return closest;
}
void dijkstra::calculate()
{
initialize();
int min = infinity;
int closest;
int count = 0;
while(count < vertices)
{
closest = unmarked();
mark[closest] = true;
for(int i=0; i<vertices; i++)
{
if((!mark[i]) && (adj[closest][i]>0))
{
if(distance[i]>distance[closest]+adj[closest][i])
{
distance[i]=distance[closest]+adj[closest][i];
predecessor[i] = closest;
}
}
}
count++;
}
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

84

void dijkstra::path(int node)


{
if(node == source)
cout << (char)(node + 65);
else if(predecessor[node] == -1)
cout << "No path from " << source << "to " << node;
else
{
path(predecessor[node]);
cout << "->" << (char) (node + 65);
}
}
void dijkstra::output()
{
for(int i=0; i<vertices; i++)
{
if(i == source)
cout <<(char)(source+65)<< "->" <<(char)(source+65);
else
path(i);
cout << " = " << distance[i] << "\n";
}
}

int main()
{
dijkstra djk;
djk.read();
djk.calculate();
cout << "Shortest path from source vertex are : \n";
djk.output();
return 0;
}

Vijai Anand

cseannauniv.blogspot.in

CS6311-PDS2 Lab Manual

85

Output
Enter number of vertices : 7
Enter adjacency matrix for the graph :
(For infinity enter 999)
999 2 999 1 999 999 999
999 999 999 3 10 999 999
999 999 999 999 999 5 999
999 999 2 999 2 8 4
999 999 999 999 999 999 6
999 999 999 999 999 999 999
999 999 999 999 999 1 999
Enter the source vertex : 0
Shortest path from source vertex are :
A->A = 0
A->B = 2
A->D->C = 3
A->D = 1
A->D->E = 3
A->D->G->F = 6
A->D->G = 5

Result
Thus Dijkstra's algorithm to find the shortest path from a given vertex is implemented.

Vijai Anand

cseannauniv.blogspot.in

Vous aimerez peut-être aussi