You are on page 1of 95

PODHIGAI COLLEGE OF ENGINEERING AND TECHNOLOGY

TIRUPATTUR 635 601.

CS6311 PROGRAMMING AND DATASTRUCTURE LAB-II

LAB MANUAL
NAME :

REGNO :

YEAR / SEM :

DEPT :

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


TABLE OF CONTENTS

PAGE
S.NO EXPERIMENT NAME SIGNATURE
NO.
CONSTRUCTORS & DESTRUCTORS, COPY
1
CONSTRUCTOR
FRIEND FUNCTION & FRIEND CLASS.
2

3 INHERITANCE

POLYMORPHISM & FUNCTION


4
OVERLOADING

5 VIRTUAL FUNCTIONS

OVERLOAD UNARY & BINARY OPERATORS


6 BOTH AS MEMBER FUNCTION & NON
MEMBER FUNCTION
CLASS TEMPLATES & FUNCTION
7
TEMPLATES

8 EXCEPTION HANDLING MECHANISM

9 STANDARD TEMPLATE LIBRARY CONCEPT

FILE STREAM CLASSES.


10

11 APPLICATIONS OF STACK AND QUEUE

12 BINARY SEARCH TREE

13 TREE TRAVERSAL TECHNIQUES

14 MINIMUM SPANNING TREES

15 SHORTEST PATH ALGORITHMS

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 1a CONSTRUCTOR

Aim

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

Algorithm

1. Start
2. Declare class distance containing data members inch and feet.
3. Define default constructor that initializes data members to 0.
4. Define parameterized constructor that initializes data members with values provided.
5. Define display function to print value of data members
6. Create distance objects to invoke the constructors.
7. Call display function for each distance object.
8. 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()

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{
cout << feet << "." << inch << "ft \n";
}
};
int main()
{
distance d1, d2(4), d3(22,7);
d1.print(); d2.print(); d3.print();
}

Output

0.0ft

4.0ft
22.7ft

Result

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 1b COPY CONSTRUCTOR
Aim

To initialize data members of an object using copy constructor.

Algorithm

1. Start
2. Declare class complex with data members real and imag
3. Define parameterized constructor that initializes data members with given values
4. Define copy constructor that uses an object reference to initialize data members of
another object
5. Define display function to print data members
6. Create complex objects that invoke copy constructor in various ways.
7. Call display function for each distance object.
8. 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) // copy constructor

{ real = c1.real; imag =


c1.imag;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

void display()

{ cout << real << " + " << imag << "i \n"; }

};

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 1c DESTRUCTOR
Aim

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

Algorithm

1. Start
2. Declare class mystring with data member str and len
3. Define dynamic constructor using new operator
4. Define display function to print string contents
5. Define destructor that releases memory using delete operator
6. Create objects using constructor and invoke destructor when they go out of scope
7. 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";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


void display()

{ cout << str << "\n";

~mystring() // Destructor

{ delete[] str;

cout << "Memory released \n";

};

int main()

{ mystring s1("PCET"); s1.display();

Output

Dynamic memory allocation

PCET

Memory released

Result

Thus memory allocated to objects were automatically released using destructor.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 2a FRIEND FUNCTION
Aim

To access data members of a class using friend function.

Algorithm

1. Start
2. Declare class sample with data members
3. Define a non-member function mean that returns aggregate of data members
4. Declare function mean as friend to class sample
5. Provide value for data members
6. Call function mean
7. 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 2b FRIEND CLASS
Aim

To demonstrate usage of friend classes

Algorithm

1. Start
2. Declare class rectangle with length and breadth as data members
3. Declare class square with side as data member
4. Declare class rectangle as friend to class square
5. Define function convert in rectangle class that takes square object as argument
6. Create objects for both classes
7. Call function convert to demonstrate friend class.
8. 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);

};

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


class square

{ friend class rectangle; int side;

public:

square (int a)

{ side = a;

};

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 3a SINGLE INHERITANCE
Aim

To demonstrate single inheritance using box class.

Algorithm

1. Start
2. Declare class rectangle with protected members length and breadth
3. Define function rectdim to read values
4. Derive class box from rectangle in public mode with data member depth.
5. Define function getdata for box class that calls rectdim function
6. Create object for box class 7. Display volume of the box.
8. 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;

};

class box : public rectangle

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ 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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 3b 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

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 : ";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


cin >> qualfn;

cout << " Enter basic pay : "; cin >> salary;

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)

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 3c 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 ;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


};

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 3d MULTILEVEL INHERITANCE
Aim
To demonstrate multilevel chain relationship amongst different classes.

Algorithm
1. Start
2. Declare class vertebrate with function eat
3. Derive class mammal from vertebrate publicly with function suckle
4. Derive class primate from mammal publicly with function peel
5. Derive class human from primate publicly with function think
6. Create object for human class
7. Call derived functions eat, suckle and peel and its own function think
8. 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";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


};

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 3e 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

void disphslc()

{ cout << "\n" << "Name : " << name << "\n"; cout << "Percentage : " <<
percent << "% \n"; }

};

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";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


} };

class pg : public ug, public gate

{ protected: int rank;

public: void getpg()

{ cout << "Enter rank : "; cin >> rank;

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 name and hslc percentage : Gowtham 68

Enter course and cgpa : B.E(CSE) 7.34

Enter gate score : 44

Enter rank : 6

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 4a 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)

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


return (a * a * a);

int volume(int l, int b, int h)

{ return (l * b * h);

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 5a 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() { }

};

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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";

};

class lorry : public vehicle

{ public: lorry()

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Output
Bicycle

Capacity : 2

Fuel : Air

Features : Green environment

Autorickshaw

Capacity : 3

Fuel : Petrol/Diesel/LPG

Features : Urban transport

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 6a UNARY OPERATOR OVERLOADING - MEMBER FUNCTION

Aim
To overload unary operator using member function.

Algorithm
1. Start
2. Declare class space with data members x, y and z
3. Define parameterized constructor for space class
4. Define display function to print data members
5. Overload unary minus () using operator member function
6. Create a space object
7. Invoke unary minus on space object 8. Call display member function.
9. 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


void operator-()

{ x = -x; y = -y; z
= -z;

};

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 6b 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()

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ cout << num << "/" << den << "\n";

friend void operator ++(fraction &);

};

void operator ++(fraction &f) // overloading using friend

f.num = f.num + f.den;

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 6c. BINARY OPERATOR OVERLOADING - MEMBER FUNCTION

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

Algorithm
1. Start
2. Declare class distance with data members inch and feet
3. Define default and parameterized constructor for distance class
4. Define display function to print data members
5. Overload operator + using operator member function
6. Create two distance object with input values.
7. 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

void display()

{ cout << feet << "." << inch << "ft \n";

distance operator +(distance); //addition (+) overloaded bool operator <(distance);


//less than(<) overloaded };

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;
}

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Output

Distance1 : 10.6ft

Distance2 : 11.6ft

Distance3 : 22.0ft

Distance1 is nearest

Result
Thus two distance objects were added using operator overloading.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 6d 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. Start
2. Declare class array1d with data members arr containing an array
3. Define getdata function to obtain input for array elements
4. Define display function to print array elements
5. Declare overloading of operator + and as friend to class array1d
6. 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()

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ 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); };

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, S, T;

cout << "Enter 5 elements for B array : ";

B.getdata(); C = 2 + B; cout
<< "2 + B = "; C.display();

cout << "\nEnter 5 elements for S array : "; S.getdata();

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


cout << "Enter 5 elements for T array : ";

T.getdata(); K = S - T; cout
<< "S - T = "; K.display();
return 0;

Output

Enter 5 elements for B array : 1 2 3 4 5

2+B=34567

Enter 5 elements for S array : 0 9 8 7 6

Enter 5 elements for T array : 2 7 3 1 4

S - T = -2 2 5 6 2

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 7a 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;
}

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}
}
}
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 Char

-4 -0.4 I 0 0.7 a
1 1.9 d3 2.2 i
5 2.7 n
8 3.5 n

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 7b CLASS TEMPLATES
Aim
To implement stack operations push and pop using class template.

Algorithm
1. Start
2. Declare a template class mystack with array data member st of template type
3. Define a default constructor that initializes top data member
4. Define push and pop operation with template arguments 5. Define function full
and empty to indicate stack full or empty
6. Create mystack objects of different types.
7. Invoke stack operations for each mystack object
8. 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

T pop()

{ return st[top--];

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> s1; // Character Stack mystack <int> 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++)

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ if (S2.isFull()) cout << "\n\nInt Stack Overflow";

else

S2.Push(i); }

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 8a EXCEPTION HANDLING
Aim
To demonstrate exception handling in C++ using try, throw and catch mechanism.

Algorithm
1. Start
2. Read two numbers a and b
3. Within try block, if b = 0 then raise exception for b
4. Otherwise execute arithmetic expression a / b
5. Define catch block to handle divide by zero exception
6. 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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 8b 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 { }; //exception class class empty { }; //exception


class

mystack()

{ top = -1;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

void push(int var)

{ if(top >= size-1) throw full(); //throw exception for stack


full

st[++top] = var;

int pop()

{ if(top < 0) throw empty(); //throw exception for stack


empty

return st[top--];

} };

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 9a C++ STRING CLASS

Aim
To demonstrate functionality of C++ string class.

Algorithm
1. Start
2. Include header file string
3. Create objects of string class
4. Call member functions insert, append, erase, replace, swap, etc on string objects
5. Display the resultant string after each function call.
6. 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 ";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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;

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 9b VECTOR

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

Algorithm
1. Start
2. Include header file vector
3. Create a vector object v1 to store integers.
4. Use push_back member function to append elements onto v1
5. Delete last element in v1 using pop_back member function
6. Display first and last element of v1 using front and back member function
7. Display length of v1 using size member function
8. Display v1 elements using a loop
9. Stop

Program
// 9b STL vector

#include <iostream>

#include <vector> using namespace std;

int main()

vector <int> v1(5); // Vector of size 5

int data, i;

cout << "Enter 5 vector elements : "; for (i=0; i<v1.size(); i++)
cin >> v1[i];

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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";

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 9c 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);

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


for (int i=2; i<10; i+=2) l3.push_front(i);

first = l2.begin(); cout << "List L2 : "; while (first !=


l2.end()) cout << *first++ << " "; 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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 9d MAPS

Aim
To demonstrate search operation on associative container STL map.

Algorithm
1. Start
2. Include header file map
3. Create map object m1 to store character and its corresponding ASCII value 4. Declare an
iterator ptr to step through map elements.
5. Populate map m1 using insert with pair member function
6. Read a character ch from the user
7. Search map m1 for the given key ch using find member function
8. If found then display corresponding ASCII value using member second
9. 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: ";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


cin >> ch; ptr = m1.find(ch); if(ptr != m1.end()) cout << "ASCII value : " << ptr-
>second;

else cout << "Key not in map"; 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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 9e STL ALGORITHM

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

Algorithm
1. Start
2. Include header file algorithm and functional
3. Initialize a float array fdata with 5 elements
4. Sort the array using sort function with greater predicate
5. Print fdata elements using a loop
6. 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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 10a 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>

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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();

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 10b 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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


{ src.open(file1); if(src.fail()) throw file1; // Source file non-existent dst.open(file2);

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 filecopy.c File copied

Result

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 10c BINARY FILE I/O SEQUENTIAL ACCESS
Aim
To write product details as a binary file and to access product records sequentially.

Algorithm
1. Start
2. Include header file fstream
3. Declare class product with data members code, name and rate.
4. Define member function getdata, putdata and prodcode for product class
5. Create object for fstream and product class as fobj and p1 respectively
6. Display file operations as menu
7. Accept choice
8. 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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Program
// 10c Objects with sequential access

#include <fstream.h>

#include <iostream.h>

class product

{ int code; char name[20];


float rate;

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 : ";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


cin >> ch; switch(ch)

{ case 1:

p1.getdata();

fobj.open("invent.dat", ios::app|ios::binary); fobj.write((char *)&p1,


sizeof(p1));

fobj.close(); break;

case 2:

cout << " Enter product code : ";

cin >> pid;

fobj.open("invent.dat", ios::in );

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


{ if (pid == p1.prodcode())

{ p1.putdata(); break;

} fobj.close(); break;

} return 0;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 10d BINARY FILE I/O RANDOM ACCESS
Aim
To write student details as a binary file and to access student records randomly.

Algorithm
1. Start
2. Include header file fstream
3. Declare class student with data members rollno, name, arrears and cgpa
4. Define member function getdata and display for student class
5. Create object for fstream and student class as fobj and s1 respectively
6. Display file operations as menu
7. Accept choice
8. 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>

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


class student

{ int rollno; char name[20]; int arrear;


float cgpa;

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


fobj.seekg((rno - 1) * sizeof(s1), ios::beg); fobj.read((char *)&s1,
sizeof(s1));

s1.display(); fobj.close();
break;

} return 0;

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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 11a TOWERS OF HANOI
Aim
To solve Towers of Hanoi problem using stack operations.

Algorithm
1. Start
2. Get number of disks, say n.
3. Push parameters and return address onto stack
4. 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.
5. Move final discs from start to destination needle.
6. Move remaining discs from intermediate to destination needle.
7. Return to previous level by popping stack.
8. 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);

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

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 : 2

Move disc 1 from A to B

Move disc 2 from A to C

Move disc 1 from B to C

Result

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 12/13a 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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Program
// 12a binary search tree and traversal

#include<iostream.h>

#include <process.h> #include<stdlib.h>

#include <malloc.h>

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 !";

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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

{ cout << "Postorder traversal is : ";

tree.postorder(root);

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


} break;

case 0:

exit (0);

} return 0;
}

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Output
Binary Search Tree

1.insert 2.preorder 3.inorder 4.postorder 0.Exit

Enter your choice : 1

Enter the new element : 5

Inorder traversal is : 5-->

Binary Search Tree

1.insert 2.preorder 3.inorder 4.postorder 0.Exit

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 0.Exit

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 0.Exit

Enter your choice : 2 Preorder traversal is : 5-->3--


>7-->

Result

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 14a PRIM'S MINIMUM SPANNING TREE
Aim
To determine edges for minimum spanning tree in the given graph using Prim's algorithm

Algorithm
1. Start
2. Define infinity to be a large number, say 999.
3. Declare class prim with requisite data members
4. 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 row 10 #define col 10

#define infi 999

#define false 0

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


#define true 1

class prims

{ int graph[row][col];

int nodes;

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()

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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;

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


int main() {

prims pmst;

cout << "Prims Algorithm \n";

pmst.create(); cout << "Edges of Minimum Spanning Tree are : \n";

pmst.findmst(); return 0;

Output
Prims Algorithm

Enter Total Nodes : 7 Enter Adjacency


Matrix :

0241000200390
0400205013207
8409070060058
001

0 004610
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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 14b KRUSKAL'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];

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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]; node1 = unvisited = i; node2 = visited =


j;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


}

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Output
Enter No. of vertex : 7 Enter adjacency
matrix(cost):

024100020039
004002050132
078409070060
058001000461
0 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.

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


Ex. 15a DIJKSTRA SHORTEST PATH
Aim

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

Algorithm

1. Start
2. Define infinity to be a large number, say 999.
3. Declare class dijkstra with requisite data members
4. 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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


c. Call output member function 11. Stop

Program
// 15a Dijkstra's shortest path algorithm

#include<iostream.h>

#define infinity 999

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;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


void dijkstra::initialize()

{ for(int i=0; i<vertices; i++)

{ mark[i] = false; predecessor[i] = -1; distance[i] =


infinity;

distance[source] = 0;

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++)

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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++;

}}

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"; }

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


int main()

{ dijkstra djk; djk.read();


djk.calculate();

cout << "Shortest path from source vertex are : \n"; djk.output(); return 0;

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G


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


84

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

III Sem -CSE /CS6311- PDS_2 Lab Manual PCET / RAJASEKARAN.G

You might also like