Sei sulla pagina 1di 164

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.

in

K.L.N. COLLEGE OF ENGINEERING


POTTAPALAYAM.P.O, SIVAGANGAI -630611.

DEPARTMENT OF INFORMATION TECHNOLOGY

CS6311-PROGRAMMING AND DATA STRUCTURE LABORATORY II

II YEAR / III SEMESTER


2014 2015 (ODD)

PREPARED BY
Dr.G.RAMESH Professor/IT

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

SYLLABUS
CS6311

PROGRAMMING AND DATA STRUCTURE LABORATORY II

LTPC
0 0 3 2

OBJECTIVES:
The student should be made to:
Be familiarized with good programming design methods, particularly Top- Down
design.
Getting exposure in implementing the different data structures using C++
Appreciate recursive algorithms.
LIST OF EXPERIMENTS:
IMPLEMENTATION IN THE FOLLOWING TOPICS:
1. Constructors & Destructors, Copy Constructor.
2. Friend Function & Friend Class.
3. Inheritance.
4. Polymorphism & Function Overloading.
5. Virtual Functions.
6. Overload Unary & Binary Operators Both as Member Function & Non Member Function.
7. Class Templates & Function Templates.
8. Exception Handling Mechanism.
9. Standard Template Library concept.
10. File Stream classes.
11. Applications of Stack and Queue
12. Binary Search Tree
13. Tree traversal Techniques
14. Minimum Spanning Trees
15. Shortest Path Algorithms
TOTAL: 45 PERIODS
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement C++ programs for manipulating stacks, queues, linked lists, trees,
and graphs.
Apply good programming design methods for program development.
Apply the different data structures for implementing solutions to practical problems.
Develop recursive programs using trees and graphs.
REFERENCE:
spoken-tutorial.org.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:
Standalone desktops with C++ compiler 30 Nos.
(or)
Server with C++ compiler supporting 30 terminals or more.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

LIST OF EXPERIMENTS
EX.NO
1

NAME OF THE EXPERIMENT


a. CONSTRUCTORS
b. DESTRUCTORS
c. COPY CONSTRUCTOR

FRIEND FUNCTION

INHERITANCE
a. POLYMORPHISM

b. FUNCTION OVERLOADING

VIRTUAL FUNCTIONS

OPERATOR OVERLOADING
a. CLASS TEMPLATES

b. FUNCTION TEMPLATES

EXCEPTION HANDLING MECHANISM

STANDARD TEMPLATE LIBRARY

10

FILE STREAM CLASSES

11

APPLICATIONS OF STACK AND QUEUE

12

BINARY SEARCH TREE

13

TREE TRAVERSAL TECHNIQUES


MINIMUM SPANNING TREES

14

a. PRIMS ALGORITHM
b. KRUSKALS ALGORITHM
SHORTEST PATH ALGORITHMS

15

a. DIJKSTRAS ALGORITHM
b. FLOYD WARSHALLS ALGORITHM.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

INTRODUCTION
OOP Concepts:
The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is
designed aroundthe data being operated upon rather upon the operations
themselves. Data and its functions areencapsulated into a single entity.OOP
facilitates creating reusable code that can eventually save alot of work. A feature
called polymorphism permits to create multiple definitions for operatorsand
functions. Another feature called inheritance permits to derive new classes from
old ones.OOP introduces many new ideas and involves a different approach to
programming than theprocedural programming.
Benefits of object oriented programming:
Data security is enforced.
Inheritance saves time.
User defined data types can be easily constructed.
Inheritance emphasizes inventions of new data types.
Large complexity in the software development can be easily managed.
Basic C++ Knowledge:
C++ began its life in Bell Labs, where Bjarne Stroustrup developed the
language in the early1980s. C++ is a powerful and flexible programming language.
Thus, with minor exceptions, C++is a superset of the C Programming
language.The principal enhancement being the object oriented concept of a class.
A Class is a user defined type that encapsulates many important mechanisms.
Classes enableprogrammers to break an application up into small, manageable
pieces, or objects.
Basic concepts of Object-oriented programming:
Object:
Objects are the basic run time entities in an object-oriented system.They
may represent a person, a place, a bank account, a table of data or any item that the
Program has to handle.
Class:
The entire set of data and code of an object can be made of a user defined
data type withthe help of a class in fact Objects are variables of the type class.
Once a class has been defined, we can create any number of objects belonging to

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

that class. A class is thus a collection ofobjects of similar type.For example:


mango, apple, and orange are members of the class fruit.
ex:
fruit mango;
will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation:
The wrapping up of data and functions in to a single unit is known as
encapsulation.Dataencapsulation is the most striking feature of a class. The data is
not access able to the outsideworld and only those functions which are wrapped in
the class can access. This insulation of thedata from direct access by the program is
called data hiding.
Abstraction:
Abstraction refers to the act of representing essential features without
including thebackground details or explanations. Since the classes use the concept
of data abstraction,they areknown as abstraction data type(ADT).
Inheritance:
Inheritance is the process by which objects of one class acquire the
properties of objects ofanother class.
ex:The bird 'robin ' is a part of the class 'flying bird' which is again a part of the
class 'bird'.The concept of inheritance provides the idea of reusability.
Polymorphism:
Polymorphism is another important oop concept. Polymorphism means the
ability to takemore than one form. An operation may exhibit different instances.
The process of making anoperator to exhibit different behaviors in different
instance is known as operator overloading.
Input/output Statements:
Cout<<example;
Cin>>n;
Class definition:
Class definition has two components: the class head, the class body.
Class vector //the class head
{
// all class members
};

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:1(a)

CONSTRUCTORS

It is convenient if an object can initialize itself when it is first created,


without need to make a separate call to its member functions. C++ provides a non
static member function called as constructor that is automatically called when
object is created. After objects are created, their members can be initialized by
using constructors.
Important points to be noted while using constructors
Constructor name must be the same as that of its class name in which it belongs.
Constructors are invoked automatically when objects are created.
Constructors cannot specify return types nor return values.
Constructors cannot be declared static or const.
Constructors should have public access within the class.
Ex: (i) Write a C++ program with constructor function.
Aim:
To write a c++ program with constructor function.
Algorithm:
step1: create a maths class
step2: declared within a maths class private int variable, constructor and a
showdata function
step3: initialize a variable a to 100 within the constructor
step4: display a value with the help of showdata function
step4: within the main function create a instance of the maths class to m
step5: call a method of showdata function using m
Program:
# include<iostream.h>
class maths
{
int a;
public:
maths();
void showdata();
};
maths :: maths()
{
cout<<\n this is a constructor;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

a=100;
}
void maths :: showdata()
{
cout<<\n the value of a=<<a;
}
void main ()
{
maths m;
m.showdata();
}
Output:
This is a constructor
The value of a=100
Result:
Thus the c++ program for constructor function is executed successfully.
Ex: (ii) Write a c++ program to calculate prime number using constructor.
Aim:
To write a c++ program to calculate prime number using constructor.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class as Prime with data members,Member functions.
Step 3: Consider the argument constructor Prime() with integerArgument.
Step 4: To cal the function calculate() and do the following steps.
Step 5: For i=2 to a/2 do
Step 6: Check if a%i==0 then set k=0 and break.
Step 7: Else set k value as 1.
Step 8: Increment the value i as 1.
Step 9: Check whether the k value is 1 or 0.
Step 10:If it is 1 then display the value is a prime number.
Step 11:Else display the value is not prime.
Step 12:Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class prime
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int a,k,i;
public:
prime(int x)
{
a=x;
}
void calculate()
{
k=1;
{
for(i=2;i<=a/2;i++)
if(a%i==0)
{
k=0;
break;
}
else
{
k=1;
}
}
}
void show()
{
if(k==1)
cout<< \n\tA is prime Number. ";
else
cout<<"\n\tA is Not prime.";
}
};
void main()
{
clrscr();
int a;
cout<<"\n\tEnter the Number:";
cin>>a;
prime obj(a);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

obj.calculate();
obj.show();
getch();
}
Output:
Enter the number: 7
Given number is Prime Number
Result:
Thus the c++ program to calculate prime number using constructor is
executed successfully.
Ex.No:1(b)

DESTRUCTORS

A destructor is a member function that is called automatically when an


object is destroyed.~class name ();Where the class name is the name of the
destructor and is preceded by a tilde (~) symbol.
Ex: Write a C++ program with destructor function.
Aim:
To write a c++ program with destructor function.
Algorithm:
step1: initialize n=0
step2: create a call class
step3: declared constructor and a destructor function within a call class
step4: display ++n value using constructor
step5: display --n value using destructor
step6: within the main function create two instances of the call class c1 and c2
Program:
#include<iostream.h>
int n=0;
class call
{
public:
call ()
{
cout<<\n constructor<<++n;
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

~call ()
{
cout<<\n destructor< --no;
}
};
main ()
{
call c1, c2;
}
Output:
constructor 1
constructor 2
destructor 1
destructor 0
Result:
Thus the c++ program for destructor function is executed successfully.
Ex.No:1(c)

COPY CONSTRUCTOR

The copy constructor is a constructor which creates an object by initializing


it with an object of the same class, which has been created previously. The copy
constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then it is
a must to have a copy constructor.
Ex: Write a C++ program to calculate factorial of a given number using copy
constructor.
Aim:
To write a c++ program to calculate factorial of a given number using copy
constructor.
Algorithm:
Step 1: start the program.
Step 2: declare the class name as copy with data members and member functions.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 3: the constructor copy() with argument to assign the value.


Step 4: to cal the function calculate() do the following steps.
Step 5: for i=1 to var do
Step 6: calculate fact*i to assign to fact.
Step 7: increment the value as 1.
Step 8: return the value fact.
Step 9: print the result.
Step 10: stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();


cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
Output:
Enter the Number: 5
Factorial is: 120
Factorial is: 120
Result:
Thus the c++ program to calculate factorial of a given number using copy
constructor is executed successfully.

Ex.No:2

FRIEND FUNCTION

A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

member functions.A friend can be a function, function template, or member


function, or a class or class template, in which case the entire class and all of its
members are friends.
Ex: Write a C++ program to find the mean value of a given number using
friend function.
Aim:
To write a c++ program to find the mean value of a given number using
friend function.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class name as Base with data members and member functions.
Step 3: The function get() is used to read the 2 inputs from the user.
Step 4: Declare the friend function mean(base ob) inside the class.
Step 5: Outside the class to define the friend function and do the following.
Step 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
Step 7: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
Result:
Thus the c++ program to find the mean value of a given number using friend
function is executed successfully.

Ex.No:3

INHERITANCE

A class has specified data type and if you need another data type similar to
the previous onewith some additional features,instead of creating a new data type,
C++ allows inheriting themembers of the existing type and can add some more
features to the new class. This property isreferred to as inheritance.The old class is
called as base class and new class is called as derivedclass or child class.The
general form or the syntax of specifying a derived class is:
Class derivedclassname :acessspecifies baseclassname

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
//body of the derived class
}
The colon indicates that, the derived class named derivedclassname is
derived from the baseclass named baseclassname. The access specifier of the base
class must be private,protectedor public.If no accessspecifier is present is assumed
private by default. The body of the derivedclass contains member data and member
functions of its own.
Single inheritance:
A derived class with only one base class is called as single
Inheritance.Thederived class can access all the members of the base class and can
add members of its own.
Ex: (i) Write a c++ program to display student information using Single
inheritance.
Aim:
To write a c++ program for student information system using single
inheritance.
Algorithm:
step1: Take two classess teacher and student
step2: withina teacher class Enter name and number values with the help of
getdata() function anddisplay this data using putdata() function.
step3: within the student class Enter and display marks m1,m2,m3 with the help of
getdata(),putdata() functions.
step4: within the student class extends teacher class and using data and their
functions to thestudent class
Program:
#include<iostream.h>
class teacher
{
private:
char name[25];
long number;
public:
void getdata()
{
cout<<\n \t Enter your name:;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cin>>name;
cout<<\n \t Enter your number:;
cin>>number;
}
void putdata()
{
cout<<\n \t name:<<name;
cout<<\n \t number : <<number;
}
};
class student : public teacher
{
private:
int m1,m2,m3;
public:
void getdata()
{
teacher :: getdata();
cout<<\n \t Enter marks in three subjects:;
cin>>m1>>m2>>m3;
}
void putdata()
{
teacher :: putdata();
cout<<\n \t Marks of three subjects:<<m1<<m2<<m3;
}
};
void main()
{
student s1,s2;
cout<<\n Enter data for student 1:\n:
s1.getdata();
cout<<\n Enter data for student2 :\n;l
s2.getdata();
cout<<\n the data of student 1:;
s1.putdata();
cout<<\n the data of student 2:;
s2.putdata();
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Output:
Enter data for student1
Enter your name:James
Enter your number:1
Enter 3 subject mark:75 65 85
Enter data for student 2
Enter your name :Susila
Enter your number:2
Enter marks in 3 subjects:65 85 75
The data for student 1
Name:James
Number:1
Marks of three subjects:75 65 85
The data for student 2
Name :Susila
Number :2
Marks of three subjects:65 85 75
Result:
Thus the c++ program to display student information using Single
inheritanceis executed successfully.
Ex: (ii) Write a c++ program to find out the payroll system using single
inheritance.
Aim:
To write a c++ program to find out the payroll system using single
inheritance.
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class emp.
Step 3: Define and declare the function get() to get the employee details.
Step 4: Declare the derived class salary.
Step 5: Declare and define the function get1() to get the salary details.
Step 6: Define the function calculate() to find the net pay.
Step 7: Define the function display().
Step 8: Create the derived class object.
Step 9: Read the number of employees.
Step 10: Call the function get(),get1() and calculate() to each employees.
Step 11: Call the display().

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 12: Stop the program.


Program:
#include<iostream.h>
#include<conio.h>
class emp
{
public:
int eno;
char name[20],des[20];
void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
};
class salary:public emp
{
float bp,hra,da,pf,np;
public:
void get1()
{
cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
void display()

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<
pf<<"\t"<<np<<"\n";
}
};
void main()
{
int i,n;
char ch;
salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();
s[i].calculate();
}
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for(i=0;i<n;i++)
{
s[i].display();
}
getch();
}
Output:
Enter the Number of employee:1
Enter the employee No: 150
Enter the employee Name: ram
Enter the designation: Manager
Enter the basic pay: 5000
Enter the HR allowance: 1000
Enter the Dearness allowance: 500
Enter the profitability Fund: 300
E.No E.name des
BP HRA DA PF
150 ram
Manager 5000 1000 500 300

NP
6200

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Result:
Thus the c++ program to find out the payroll system using single
inheritanceis executed successfully.
Multiple Inheritances:
Very often situations may arise in which a class has to derive featuresfrom
more than one class. Multiple inheritancesfacilitate a class to inherit features from
morethan one class. The derived class can access two or more classes and can add
properties of itsown.
Ex: (iii) Write a program for employee database using multiple inheritances.
Aim:
To write a c++ program for employee database using multiple inheritance.
Algorithm:
step1:Take three classess student,employee,manager
step2:withina student class Enter name and school, college data with the help of
getdata()function and display this data using putdata() function.
step3:within the employee class Enter and display company, age data with the help
ofgetdata(),putdata() functions.
step4:within the manager class extends student and employee classess and using
data and theirfunctions to the manager class and Enter & display disegnation
,salary of the manager usingputdata(),getdata() functions
step5:within the main function create instance of manager class m and call
getdata() andputdata() functions.
Program:
#include<iostream.h>
#include<conio.h>
const int max=50;
class student
{
private:
char name[max];
char school[max];
char college[max];
public:
void getdata()
{
cout<<\n \t enter name :;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cin>>name;
cout<<\t enter school name:;
cin>school;
cout<<\n \t enter college name:;
cin>>college;
}
void putdata()
{
cout<<\n \t name :<<name;
cout<<\n \t school name :<<school;
cout<<\n \t college name :<<college;
}
};
class employee
{
private
char company[max];
int age;
public :
void getdata()
{
cout<<\n \t enter the company name :;
cin>>company;
cout<<\n \t enter age:;
cin>>age;
}
void putdata()
{
cout<<\n \t company name :<<company;
cout<<\t age:<<age;
}
};
class manager : private employee,private student
{
private:
char design[max];
float salary;
public :
void getdata()
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

student ::getdata();
employee ::getdata();
cout<<\n \t enter your designation :;
cin>>design;
cout<<\n \t enter salary:;
cin>>salary;
}
void putdata()
{
student ::putdata();
employee::putdata();
cout<<\n \t designation :<<design;
cout<<\n \t salary :<<salary;
}
};
void main(0
{
manager m;
clrscr();
cout<<\n enter data for manager:<<endl;
m.gatdata();
cout<<\n the data for manager is :<<endl;
m.putdata();
}
Output:
Enter data for manager :
Enter name : Ram
Enter name of school: GMSS
Enter name of college :GCET
Enter name of company :CMC
Enter age :24
Enter designation :Analyst
Enter salary :10000
The data for manager is
Student Name :Ram
School Name :GMSS
College Name :GCET
Company Name :CMC
Age :24
Designation :Analyst

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Salary:10000
Result:
Thus the c++ program for employee database using multiple inheritancesis
executed successfully.

Ex.No:4(a)

POLYMORPHISM

The word polymorphism means having many forms. Typically,


polymorphism occurs when there is a hierarchy of classes and they are related by
inheritance.C++ polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that invokes the
function.
Ex: Write a c++ program to explain the concept of polymorphism.
Aim:
To write a c++ program for polymorphism.
Program:
#include <iostream>
using namespace std;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class Shape
{
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

// store the address of Rectangle


shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
Output:
Rectangleclass area
Triangleclass area
Result:
Thus the c++ program for polymorphism is executed successfully.

Ex.No:4(b)

FUNCTION OVERLOADING

C++ enables two or more functions with same name but with different types
of arguments orwith different number of arguments .This capability to overload a
function is called functionoverloading.
Ex: (i) Write a c++ program to explain function overloading with different
number of arguments.
Aim:
To write a c++ program to explain function overloading with different
number of arguments.
Algorithm:
step1:create two functions with the same name and same data type but different
number of
arguments
step2: within the main function initialize integer values x=5,y=10,z=20,a=0,b=0

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

step3:a)s=call sum(x,y)
print s
b) s=call sum(x,y,z)
prin ts
step4:a)with in the called function of sum(x,y)
return x+y
b)with in the called function of sum(x,y,z)
return x+y+z
Program:
#include<iostream.h>
#include<conio.h>
int sum(int, int);
int sum(int, int, int)
void main()
{
int x=5,y=10,z=20,a=0,b=0;
clrscr();
a=sum(x,y);
b=sum(x,y,z);
cout<< sum of two integers=<<a<<endl;
cout<<sum of three integers=<<b<<endl;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
Output:
sum of two intezers=15
sum of three integers=35
Result:
Thus the c++ program for function overloading with different number of
argumentsis executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex: (ii) Write a c++ program to explain function overloading with type, order,
and sequence of arguments.
Aim:
To write a c++ program to explain function overloading with type, order,
and sequence of arguments.
Algorithm:
step1: create more functions with the same name and different data types and
different number of arguments
step2: within the main function initialize different data type variables
step3:a)sum=call all functions print sum
step4:a)write all called functions return sum of values
Program:
#include<iostream.h>
#include<conio.h>
int sum(int,int);
int sum(int,int,int);
float sum(float,int,float);
double sum(double,float);
double sum(int,float,double);
long double sum(long double,double);
void main()
{
int a=sum(4,6);
int b=sum(2,4,6);
float c=sum(3.5f,7,5.6f);
double d=sum(7,8,1.2f);
double e=sum(1,2.2f,8.6);
long double f=sum(100,80);
clrscr();
cout<<sum(int,int) =<<a<<endl;
cout<< sum(int,int,int) =<<b<<endl;
cout<<sum(float,int,float) =<<c<<endl;
cout<< sum(double,float) =<<d<<endl;
cout<< sum(int,float,double) =<<e<<endl;\
cout<<sum(long double,double) = <<f;
getch();
}
int sum(int x,int y)

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
float sum(float x,int y,float z)
{
return(x+y+z);
}
double sum(double x,float y)
{
return(x+y);
}
double sum(int x,float y,double z)
{
return(x+y);
}
long double sum(long double x,double y)
{
return(x+y);
}
Output:
sum(int,int) =10
sum(int,int,int) =12
sum(float,int,float) =16.1
sum(double,float) =9
sum(int,float,double) =11.8
sum(long,double,double) =180
Result:
Thus the c++ program for function overloading with type, order, and
sequence of argumentsis executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No: 5

VIRTUAL FUNCTIONS

Virtual means existing in effect but not in reality. A virtual function is one
that does notreally exist but nevertheless appears real to some parts of program.
Virtual functions provide away for a program to decide, when it is running, what
function to call. Virtual function allowsgreater flexibility in performing the same
kinds of action, on different kind of objects.
While using virtual functions:
It should be a member function of a class.
Static member functions cannot be virtual functions.
A virtual function should be declared in the base class specifications.
A virtual function may or may not have function body.
Virtual functions can be overloaded.
Constructors cannot be declared as virtual functions.
There can be virtual destructors.
Ex: Write a program to explain virtual functions.
Aim:
To write a c++ program for virtual function.
Algorithm:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 1: Start the program.


Step 2: Declare the base class base.
Step 3: Declare and define the virtual function show().
Step 4: Declare and define the function display().
Step 5: Create the derived class from the base class.
Step 6: Declare and define the functions display() and show().
Step 7: Create the base class object and pointer variable.
Step 8: Call the functions display() and show() using the base class object and
pointer.
Step 9: Create the derived class object and call the functions display() and show()
using the derived class object and pointer.
Step 10: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n Base class show:";
}
void display()
{
cout<<"\n Base class display:" ;
}
};
class drive:public base
{
public:
void display()
{
cout<<"\n Drive class display:";
}
void show()
{
cout<<"\n Drive class show:";
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

};
void main()
{
clrscr();
base obj1;
base *p;
cout<<"\n\t P points to base:\n" ;
p=&obj1;
p->display();
p->show();
cout<<"\n\n\t P points to drive:\n";
drive obj2;
p=&obj2;
p->display();
p->show();
getch();
}
Output:
P points to Base
Base class display
Base class show
P points to Drive
Base class Display
Drive class Show
Result:
Thus the c++ program for virtual function is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:6

OPERATOR OVERLOADING

We know that operator is a symbol that performs some operations on one or


more operands. The ability to overload operators is one of the C++s most
powerful features++ allowsus to provide new definitions to some built in
operators. We can give several meaning to anoperator, depending upon the types of
arguments used. This capability to overload an operator iscalled operator
overloading.Operators are overloaded by creating operator functions.An operator
function consists of a function definition, similar to a normal function except that
the function name nowbecomes the keyword OPERATOR followed by the symbol
being overloaded. The general formor syntax of an operator function is:
Return type class name:: operator <operator symbol>(argument list)
{
//Body of the function
}
Where return type is the data type of the value return after the specific
operation, operatorsymbol is the operator being overloaded, that is preceded by the
keyword operator, and Operatorfunction is usually a member function or a friend
function.An operator that deals with only one operand is called as a unary operator.
Some of thecommonly used unary operators are ++,--,!,~ and unary
minus.Overloading increment and decrement operators: The increment operator
(++) and the decrementoperator ( _ _ ) are unary operators since they act on only
one operand. Both the increment anddecrement operators have two forms. They are
prefix(i.e do the operation and then use thecontent of the variable.) and postfix (i.e

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

use the content of the variable and then do theoperation)notation. The general
syntax form or the syntax of the prefix and postfix operatorfunctions are
//prefix increment
return type operator++()
{
// Body of the prefix operator
}
//postfix increment
Return operator++(int x)
{
//body of the postfix operator
}

Ex: (i) Write a program to find the complex numbers using unary operator
overloading.
Aim:
To write a program to find the complex numbers using unary operator
overloading.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator ++ to increment the values
Step 6: Define the function operator - -to decrement the values.
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue
Step 10: Call the function operator ++() by incrementing the class object and call
the function display.
Step 11: Call the function operator - -() by decrementing the class object and call
the function display.
Step 12: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{
cout<<"Enter the Two Numbers:";
cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
b=--b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

obj.display();
getch();
}
Output:
Enter the two numbers: 3 6
Increment Complex Number
4+
7i
Decrement Complex Number
3+
6i
Result:
Thus the c++ programto find the complex numbers using unary
operator overloading is executed successfully.
Ex: (ii) Write a program to add two complex numbers using binary operator
overloading.
Aim:
To write a program to add two complex numbers using binary operator
overloading.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers.
Step 6: Define the function operator ()to subtract two complex numbers.
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator +
and operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class complex
{
int a,b;
public:
void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";
cin>>a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a=a+ob.a;
t.b=b+ob.b;
return(t);
}
complex operator-(complex ob)
{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};
void main()
{
clrscr();
complex obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"Input Values:\n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();
getch();
}
Output:
Enter the value of Complex Numbers a, b
4
5
Enter the value of Complex Numbers a, b
2
2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
2 + 3i
Result:
Thus the c++ programto add two complex numbers using binary
operator overloading is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:7(a)

FUNCTION TEMPLATES

Templates are the foundation of generic programming, which


involveswriting code in a way that is independent of any particular type.A template
is a blueprint or formula for creating a generic class or a function. The library
ontainers like iterators and algorithms are examples of generic programming and
have been developed using template concept.There is a single definition of each
container, such as vector, but we can define many different kinds of vectors for
example, vector <int> or vector <string>.You can use templates to define
functions as well as classes.The general form of a template function definition is
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Ex: Write a c++ program to swap the numbers using function template.
Aim:
To swap the numbers using the concept of function template.
Algorithm:
Step 1: start the program.
Step 2: declare the template class.
Step 3: declare and define the functions to swap the values.
Step 4: declare and define the functions to get the values.
Step 5: read the values and call the corresponding functions.
Step6: display the results.
Step 7: stop the program.
Program:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"\na and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\na and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\nc and d after swaping :"<<c<<"\t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"enter a,b values(integer):";
cin>>a>>b;
cout<<"enter c,d values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
Output:
enter a, b values (integer): 10 20
enter c, d values (float): 2.50 10.80
a and b before swapping: 10 20

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

a and b after swapping: 20 10


c and d before swapping: 2.50 10.80
c and d after swapping: 10.80 2.50
Result:
Thus the c++ program to swap the numbers using function templateis
executed successfully.

Ex.No:7(b)

CLASS TEMPLATES

Just like we can create function templates, we can also create class
templates, allowing classes to have members that use template parameters as types.
Ex: Write a c++ program to find the greater of two numbers using class
template.
Aim:
To write a c++ program to find the greater of two numbers using class
template.
Algorithm:
Step 1: start the program.
Step 2: declare the template class.
Step 3: declare and define the functions to swap the values.
Step 4: declare and define the functions to get the values.
Step 5: read the values and call the corresponding functions.
Step6: display the results.
Step 7: stop the program.
Program:
#include <iostream>
using namespace std;
template <class T>
class mypair {
T a, b;
public:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

mypair (T first, T second)


{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
Output:
100
Result:
Thus the c++ program to find the greater of two numbers using class
templateis executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:8

EXCEPTION HANDLING MECHANISM

An exception is a problem that arises during the execution of a program. A


C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.Exceptions provide a way
to transfer control from one part of a program to another. C++ exception handling
is built upon three keywords: try, catch, and throw.
throw: A program throws an exception when a problem shows up. This is done
using a throwkeyword.
catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception
using a combination of thetry and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the
following:
try
{
// protected code
}catch(ExceptionName e1 )
{
// catch block
}catch(ExceptionName e2 )
{
// catch block
}catch(ExceptionName eN )
{
// catch block
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex: Write a c++ program to perform exception handling for divide by zero
exception.
Aim:
To perform exception handling for Divide by zero Exception.
Algorithm:
Step 1: Start the program.
Step 2: Declare the variables a,b,c.
Step 3: Read the values a,b,c,.
Step 4: Inside the try block check the condition.
a. if(a-b!=0) then calculate the value of d and display.
b. otherwise throw the exception.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;
try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
}
catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}
getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40
Answer is infinite because a-b is: 0
Result:
Thus the c++ program for exception handling for Divide by zero Exceptionis
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:9

STANDARD TEMPLATE LIBRARY

The C++ STL (Standard Template Library) is a powerful set of C++


template classes to provide general-purpose templatized classes and functions that
implement many popular and commonly used algorithms and data structures like
vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library is following three wellstructured components:
Component

Description

Containers

Containers are used to manage collections of objects of a certain kind.


There are several different types of containers like deque, list, vector,
map etc.

Algorithms

Algorithms act on containers. They provide the means by which you


will perform initialization, sorting, searching, and transforming of the
contents of containers.

Iterators

Iterators are used to step through the elements of collections of


objects. These collections may be containers or subsets of containers.

Ex: Write a c++ program to demonstrate the standard template library using
vector container.
Aim:
To write a c++ program to demonstrates the standard template library
(vector container).
Algorithm:
Step 1: Start the program.
Step 2: create a vector to store int.
Step 3: display the original size of vec.
Step 4: push 5 values into the vector.
Step 5: display extended size of vec.
Step 6: access 5 values from the vector.
Step 7: use iterator to access the values.
Step 8: Stop the program.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Program:
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout <<"vector size = "<< vec.size()<< endl;
// push 5 values into the vector
for(i =0; i <5; i++){
vec.push_back(i);
}
// display extended size of vec
cout <<"extended vector size = "<< vec.size()<< endl;
// access 5 values from the vector
for(i =0; i <5; i++){
cout <<"value of vec ["<< i <<"] = "<< vec[i]<< endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()){
cout <<"value of v = "<<*v << endl;
v++;
}
return0;
}
Output:
vector size =0
extended vector size =5
value of vec [0]=0
value of vec [1]=1
value of vec [2]=2
value of vec [3]=3
value of vec [4]=4
value of v =0
value of v =1

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

value of v =2
value of v =3
value of v =4
Result:
Thus the c++ program for standard template library (vector container)is
executed successfully.

Ex.No:10

FILE STREAM CLASSES

File stream classes includes the operations opening and closing a file, read
from a file and write into the file. This requires a standard c++ library
called fstream, which defines three new data types:
Data Type
Description

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

ofstream

This data type represents the output file stream and is used to create files
and to write information to files.

ifstream

This data type represents the input file stream and is used to read
information from files.

fstream

This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can create files,
write information to files, and read information from files.

Ex: Write a c++ program for read & write file operation to convert lowercase
to uppercase.
Aim:
To write a c++ program for read & write file operation to convert lowercase
to uppercase.
Algorithm:
Step 1: start the program.
Step 2: declare the variables.
Step 3: read the file name.
Step 4: open the file to write the contents.
Step 5: writing the file contents up to reach a particular condition.
Step6: write the file contents as uppercase.
Step7: open the file to read the contents.
Step 8: Stop the program.
Program:
#include<fstream.h>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<iostream.h>
#include<conio.h>
void main()
{
char c,u;
char fname[10];
clrscr();
ofstream out;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"Enter File Name:";


cin>>fname;
out.open(fname);
cout<<"Enter the text(Enter # at end)\n"; //write contents to file
while((c=getchar())!='#')
{
u=c-32;
out<<u;
}
out.close();
ifstream in(fname);
//read the contents of file
cout<<"\n\n\t\tThe File contains\n\n";
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
Output:
Enter File Name: two.txt
Enter contents to store in file (enter # at end)
oops programming
The File Contains
OOPS PROGRAMMING
Result:
Thus the c++ program for read & write file operation to convert lowercase to
uppercaseis executed successfully.
Ex.No:11

APPLICATIONS OF STACK AND QUEUE

A stack is a basic data structure that can be logically thought as linear


structure represented by a real physical stack or pile, a structure where insertion
and deletion of items takes place at one end called top of the stack where as in
queue insertion and deletion of items takes place at front and rear.
Ex:(i) Write a c++ program to convert infix expression into postfix expression.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Aim:
To write a c++ program to convert infix expression into postfix expression.
Algorithm:
Step 1: Read an character input
Step 2: Actions to be performed at end of each input
Step 2.1:Opening brackets - Push into stack and then Go to step (1)
Step 2.2: Number - Print and then Go to step (1)
Step 2.3: Operator - Push into stack and then Go to step (1)
Step 2.4:Closing brackets - Pop it from the stack
Step2.4.1: If it is an operator, print it, Go to step (1)
Step2.4.2: If the popped element is an opening bracket,discard it and go to step (1)
Step 2.5: New line character - STOP
Program:
#include<iostream>
#include<vector>
#include<stack>
usingnamespace std;
staticint precedence(char x)//check precedence of operators
{
if(x=='(')
return0;
elseif(x=='+'||x=='-')
return1;
elseif(x=='*'||x=='/'||x=='%')
return2;
return3;
}
std::string infix_to_postfix(const std::string& infix)
{
std::stack<char> s;
std::string postfix;
for(auto ch : infix)
{
if(isalnum(ch))
postfix.push_back(ch);
elseif(ch =='(')
s.push(ch);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

elseif(ch ==')')
{
while(!s.empty())
{
ch = s.top();
s.pop();
if(ch =='(')
break;
postfix.push_back(ch);
}
}
else
{
while(!s.empty()&& precedence(ch)<=precedence(s.top()))
{
postfix.push_back(s.top());
s.pop();
}
s.push(ch);
}
}
while(!s.empty())
{
postfix.push_back(s.top());
s.pop();
}
return postfix;
}
int main()
{
constchar infix[]="(((8 + 1) - (7 - 4)) / (11 - 9))";
cout <<"\nThe equivalent postfix expression is: "<< infix_to_postfix(infix);
return0;
}
Output:
The equivalent postfix expression is:8 1 + 7 4 - - 11 9 - /
Result:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Thus the program for infix to postfix expression conversion is executed


successfully.
Ex: (ii) Write a c++ program to evaluate an expression using Stack
Aim:
To write a c++ program to evaluate an expression using Stack.
Algorithm:
Step 1: Start the program.
Step 2: Read a character input.
Step 3: If the character input is a number push it into a stack.
Step 4: If the character input is a symbol pop the top two numbers and perform the
corresponding operation and push it back to the stack.
Step 5: Repeat step 3 and 4 for all the input characters.
Step 6: Stop the program.
Program:
#include <iostream>
#include <conio.h>
#include <string.h>
usingnamespace std;
struct node
{
int data;
node *next;
}*p =NULL, *top =NULL, *save =NULL, *ptr;
void push(int x)
{
p =new node;
p->data = x;
p->next =NULL;
if(top ==NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
}
char pop()
{
if(top ==NULL)
{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
char x[30];
int a, b;
cout<<"enter the balanced expression\n";
cin>>x;
for(int i =0; i <strlen(x); i++)
{
if(x[i]>=48&& x[i]<=57)
push(x[i]-'0');
elseif(x[i]>=42&& x[i]<=47)
{
a=pop();
b=pop();
switch(x[i])
{
case'+':
push(a+b);
break;
case'-':
push(a-b);
break;
case'*':
push(a*b);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

break;
case'/':
push(a/b);
break;
}
}
}
cout<<"ans is "<<pop()<<endl;
getch();
}
Output:
enter the balanced expression
567+8-/
ans is -1
Result:
Thus the program to evaluate an expression using Stack is executed
successfully.

Ex.No:12

BINARY SEARCH TREE

A binary search tree is a tree where each node has a left and right child.
Either child, or both children, may be missing. Assuming k represents the value of
a given node, and then a binary search tree also has the following property: all
children to the left of the node have values smaller than k, and all children to the
right of the node have values larger than k. The top of a tree is known as the root,
and the exposed nodes at the bottom are known as leaves.The height of a tree is the
length of the longest path from root to leaf.
Ex: Write a C++ program to perform the following operations in a binary
search tree:a) Insert an elementb) Delete an element c) Search for a key
element d) Find smallest node e) Find largest node f) Determine height g) Find
total nodes.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Aim:
To write a c++ program to perform the following operations in a binary
search tree: a) Insert an element b) Delete an element c) Search for a key element
d) Find smallest node e) Find largest node f) Determine height g) Find total nodes.
Algorithm:
Step 1: Start the program.
Step 2: Include necessary header files.
Step 3: Create a structure for the input data, left and right nodes.
Step 4: If the tree is null create a node and insert the data.
Step 5: Make the left and right sub tree as null.
Step 6: If the tree is not null check the item with a root node.
Step 7: If it is lesser insert it in the left sub tree else insert it in the right sub tree.
Step 8: For deleting check the item with a root node
Step 9: If it is lesser check it in the left sub tree else check it in the right sub tree
and delete the item.
Step 10: The left leaf node is the smallest node and the right leaf node is a largest
node.
Step 11: The total number of nodes are calculated using the function totalnode.
Step 12: Height of the tree determines the levels of the tree.
Step 13:Stop the program.
Program:
#include <iostream.h>
#include <process.h>//for exit(1)
#include <conio.h>
struct node{
int data;
struct node *left;
struct node *right;
};
class BST{
public:
node *tree;
BST(){
tree=NULL;
}
void createTree(node **,int item); //For Building Tree
void determineHeight(node *,int *);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int totalNodes(node *);


node **searchElement(node **,int);
void findSmallestNode(node *);
void findLargestNode(node *);
void deleteNode(int);
};
//it is used for inserting a single element in//a tree, but if calls more than once will
create tree.
void BST :: createTree(node **tree,int item){
if(*tree == NULL){
*tree = new node;
(*tree)->data = item;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
else{
if( (*tree)->data > item)
createTree( &((*tree)->left),item);
else
createTree( &((*tree)->right),item);
}
}
void BST :: determineHeight(node *tree, int *height){
int left_height, right_height;
if( tree == NULL)
*height = 0;
else{
determineHeight(tree->left, &left_height);
determineHeight(tree->right, &right_height);
if( left_height > right_height)
*height = left_height + 1;
else
*height = right_height + 1;
}
}
int BST :: totalNodes(node *tree){
if( tree == NULL)

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

return 0;
elsereturn( totalNodes(tree->left) + totalNodes(tree->right) + 1 );
}
node ** BST :: searchElement(node **tree, int item){
if( ((*tree)->data == item) || ( (*tree) == NULL) )
return tree;
elseif( item < (*tree)->data)
return searchElement( &(*tree)->left, item);
elsereturn searchElement( &(*tree)->right, item);
}
void BST :: findSmallestNode(node *tree){
if( tree==NULL || tree->left==NULL)
cout<< tree->data;
else
findSmallestNode( tree->left);
}
void BST :: findLargestNode(node *tree){
if( tree==NULL || tree->right==NULL)
cout<<tree->data;
else
findLargestNode(tree->right);
}
void BST :: deleteNode(int item){
node *curr=tree,*succ,*pred;
int flag=0,delcase;
//step to find location of node
while(curr!=NULL && flag!=1)
{
if(item < curr->data){
pred = curr;
curr = curr->left;
}
elseif(item > curr->data){
pred = curr;
curr = curr->right;
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

else{ //curr->data = item


flag=1;
}
}
if(flag==0){
cout<<"\nItem does not exist : No deletion\n";
getch();
goto end;
}
//Decide the case of deletion
if(curr->left==NULL && curr->right==NULL)
delcase=1; //Node has no childelse
if(curr->left!=NULL && curr->right!=NULL)
delcase=3; //Node contains both the childelse
delcase=2; //Node contains only one child
//Deletion Case 1
if(delcase==1){
if(pred->left == curr) //if the node is a left child
pred->left=NULL; //set pointer of its parentelse
pred->right=NULL;
delete(curr); //Return deleted node to the memory bank.
}
//Deletion Case 2
if(delcase==2){
if(pred->left==curr){ //if the node is a left childif(curr->left==NULL)
pred->left=curr->right;
else
pred->left=curr->left;
}
else{ //pred->right=currif(curr->left==NULL)
pred->right=curr->right;
else
pred->right=curr->left;
}
delete(curr);
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

//Deletion case 3
if(delcase==3){
succ = find_Insucc(curr); //Find the in_order successor//of the node.int item1
= succ->data;
deleteNode(item1); //Delete the inorder successor
curr->data = item1; //Replace the data with the data of//in order successor.
}
end:
}
void main(){
BST obj;
int choice;
int height=0,total=0,n,item;
node **tmp;
while(1){
clrscr();
cout<<"*****BINARY SEARCH TREE OPERATIONS*****\n\n";
cout<<"1) Create Tree\n";
cout<<"2) Insert Node\n";
cout<<"3) Delete Node\n";
cout<<"4) Height of Tree\n";
cout<<"5) Total Nodes\n";
cout<<"6) Search Node\n";
cout<<"7) Find Smallest Node\n";
cout<<"8) Find Largest Node\n";
cout<<"9) Exit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1 : //Create Tree
cout<<"\n\n--Creating Tree--";
cout<<"\nHow many nodes u want to enter : ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"Enter value : ";
cin>>item;
obj.createTree(&obj.tree,item);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
break;
case 2 : //Inserting a node in a tree
cout<<"\n\n--Inserting Node in a tree--\n";
cout<<"Enter value : ";
cin>>item;
obj.createTree(&obj.tree,item);
cout<<"\nItem is inserted\n";
getch();
break;
case 3 : //Deleting a node from a tree
cout<<"\n\n--Deleting a Node from a tree--\n";
cout<<"Enter value : ";
cin>>item;
obj.deleteNode(item);
break;
case 4 : //Determining Height of Tree
obj.determineHeight(obj.tree,&height);
cout<<"\n\nHeight of Tree : "<<height;
getch();
break;
case 5 : //Total nodes in a tree
total=obj.totalNodes(obj.tree);
cout<<"\n\nTotal Nodes : "<<total;
getch();
break;
case 6 : //Search element
cout<<"\n\n--Search Element--\n";
cout<<"Enter item to searched : ";
cin>>item;
&(*tmp) = obj.searchElement(&obj.tree,item);
if( (*tmp) == NULL)
cout<<"\nSearch Element Not Found";
else
cout<<"\nSearch Element was Found";
getch();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

break;
case 7 : //Find Smallest Node
cout<<"\n\nSmallest Node is : ";
obj.findSmallestNode(obj.tree);
getch();
break;
case 8 : //Find Largest Node
cout<<"\n\nLargest Node is : ";
obj.findLargestNode(obj.tree);
getch();
break;
case 9 :
exit(1);
}//end of switch
}
}
Output:
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 1
--Creating Tree
How many nodes u want to enter : 4
Enter value : 12
Enter value : 34
Enter value : 45
Enter value : 67
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 5
Total Nodes: 4
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 6
--Search Element-Enter item to searched : 10
Search Element Not Found
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 6
--Search Element-Enter item to searched : 12
Element was Found

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

*****BINARY SEARCH TREE OPERATIONS*****


1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 7
Smallest node is: 12
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 8
Largest node is: 67
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 9
Result:
Thus the program for binary search tree operations is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:13

TREE TRAVERSAL TECHNIQUES

Ex: Write a C++ program to traverse the given binary tree in a)preorder b)inorder
c)post order
Aim:
To write a C++ program to traverse the given binary tree in a)preorder
b)inorder c)post order.
Algorithm:
Step 1: Start the program.
Step 2: Include necessary header files.
Step 3: Create a structure for the input data, left and right nodes.
Step 4: If the tree is null create a node and insert the data.
Step 5: Make the left and right sub tree as null.
Step 6: If the tree is not null check the item with a root node.
Step 7: If it is lesser insert it in the left sub tree else insert it in the right sub tree.
Step 8: In-order: traverse left first then root then right nodes.
Step 7:Preorder: traverse root first then left then right nodes.
Step 7:Post-order: traverse left first then right then root nodes.
Step 7: Stop the program.
Program:
#include <iostream.h>
#include <process.h>//for exit(1)
#include <conio.h>
struct node{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int data;
struct node *left;
struct node *right;
};
class BST{
public:
node *tree;
BST(){
tree=NULL;
}
void createTree(node **,int item); //For Building Tree
void preOrder(node *); //For Tree Traversal
void inOrder(node *);
void postOrder(node *);
//it is used for insertinga single element in a tree, but if calls more than once will
create tree.
void BST :: createTree(node **tree,int item){
if(*tree == NULL){
*tree = new node;
(*tree)->data = item;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
else{
if( (*(tree)->data > item)
createTree( &((*tree)->left),item);
else
createTree( &((*tree)->right),item);
}
}
void BST :: preOrder(node *tree){
if( tree!=NULL){
cout<<" "<< tree->data;
preOrder(tree->left);
preOrder(tree->right);
}
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

void BST :: inOrder(node *tree){


if( tree!=NULL){
inOrder( tree->left);
cout<<" "<< tree->data;
inOrder(tree->right);
}
}
void BST :: postOrder(node *tree){
if( tree!=NULL){
postOrder( tree->left);
postOrder( tree->right);
cout<<" "<<tree->data;
}
}
void main(){
BST obj;
int choice;
node **tmp;
while(1){
clrscr();
cout<<"Tree Traversal\n";
cout<<"1) Create Tree\n";
cout<<"2) Inorder Traversal \n";
cout<<"3) Preorder Traversal \n";
cout<<"4) Postorder Traversal \n";
cout<<"5) Exit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1 : //Create Tree
cout<<"\n\n--Creating Tree--";
cout<<"\nHow many nodes u want to enter : ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"Enter value : ";
cin>>item;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

obj.createTree(&obj.tree,item);
}
break;
case 2 :
cout<<"\n\nInorder Traversal : ";
obj.inOrder(obj.tree);
getch();
break;
case 3 :
cout<<"\n\nPreorder Traversal : ";
obj.preOrder(obj.tree);
getch();
break;
case 4 :
cout<<"\n\nPostorder Traversal : ";
obj.postOrder(obj.tree);
getch();
break;
case 5 :
exit(1);
}//end of switch
}
}
Output:
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 1
--Creating Tree
How many nodes u want to enter : 4
Enter value : 12
Enter value : 34
Enter value : 45
Enter value : 67

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 2
Inorder Traversal : 12 34 45 67
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 3
Preorder Traversal :12 45 34 67
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 4
Postorder Traversal : 34 67 45 12
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 5
Result:
Thus the program for binary search tree traversal operations is executed
successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:14

MINIMUM SPANNING TREES

Given a connected, undirected graph, a spanning tree of that graph is a sub


graph that is a tree and connects all the verticestogether. A single graph can have
many different spanning trees. We can also assign a weight to each edge, which is
a number representing how unfavorable it is, and use this to assign a weight to a
spanning tree by computing the sum of the weights of the edges in that spanning
tree. A minimum spanning tree (MST) or minimum weight spanning tree is then a
spanning tree with weight less than or equal to the weight of every other spanning
tree.
Ex: (i) Write a c++ program for minimum spanning tree using Kruskal's
algorithm.
Aim:
To write a c++ program for minimum spanning tree using Kruskal's
algorithm.
Algorithm:
Step1: start the program.
Step2: sort the edges of G in increasing order by length
Step3: keep a subgraph S of G, initially empty
Step4: for each edge e in sorted order
Step5: if the endpoints of e are disconnected in S
Step6: add e to S
Step7: return S
Step8: Stop the program
Program:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,m,c,visit,visited[10],l,v,count,count1,vst,p;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

main()
{
int dup1,dup2;
cout<<"enter no of vertices";
cin >> n;
cout <<"enter no of edges";
cin >>m;
cout <<"EDGE Cost";
for(k=1;k<=m;k++)
{
cin >>i >>j >>c;
cost[i][j]=c;
cost[j][i]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
visit=1;
while(visit<n)
{
v=31999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]!=31999 && cost[i][j]<v && cost[i][j]!=-1 )
{
int count =0;
for(p=1;p<=n;p++)
{
if(visited[p]==i || visited[p]==j)
count++;
}
if(count >= 2)
{
for(p=1;p<=n;p++)
if(cost[i][p]!=31999 && p!=j)
dup1=p;
for(p=1;p<=n;p++)
if(cost[j][p]!=31999 && p!=i)
dup2=p;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

if(cost[dup1][dup2]==-1)
continue;
}
l=i; k=j;
v=cost[i][j];
}
cout <<"edge from " <<l <<"-->"<<k;
cost[l][k]=-1;
cost[k][l]=-1;
visit++;
int count=0;
count1=0;
for(i=1;i<=n;i++)
{
if(visited[i]==l)
count++;
if(visited[i]==k)
count1++;
}
if(count==0)
visited[++vst]=l;
if(count1==0)
visited[++vst]=k;
}
}
Output:
enter no of vertices4
enter no of edges4
EDGE Cost
121
232
343
133
edge from 1>2edge from 2>3 edge from 1>3
Result:
Thus the program for minimum spanning tree using Kruskal's algorithm is
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex: (ii) Write a c++ program for minimum spanning tree using Prims
algorithm.
Aim:
To write a c++ program for minimum spanning tree using Prim's algorithm.

Algorithm:
Step1: start the program.
Step2: let T be a single vertex x
Step3: while (T has fewer than n vertices)
Step4: find the smallest edge connecting T to G-T
Step5: add it to T
Step6: repeat step 4 and 5 for all n vertices
Step7: Stop the program
Program:
#include <iostream.h>
#include <conio.h>
#define ROW 7
#define COL 7
#define infi 5000 //infi for infinityclass prims
{
int graph[ROW][COL],nodes;
public:
prims();
void createGraph();
void primsAlgo();
};
prims :: prims(){
for(int i=0;i<ROW;i++)
for(int j=0;j<COL;j++)
graph[i][j]=0;
}
void prims :: createGraph(){
int i,j;
cout<<"Enter Total Nodes : ";
cin>>nodes;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"\n\nEnter Adjacency Matrix : \n";


for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
cin>>graph[i][j];
//Assign infinity to all graph[i][j] where weight is 0.for(i=0;i<nodes;i++){
for(j=0;j<nodes;j++){
if(graph[i][j]==0)
graph[i][j]=infi;
}
}
}
void prims :: primsAlgo(){
int selected[ROW],i,j,ne; //ne for no. of edgesintfalse=0,true=1,min,x,y;
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<<"\n"<<x+1<<" --> "<<y+1;
ne=ne+1;
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
void main(){
prims MST;
clrscr();
cout<<"\nPrims Algorithm to find Minimum Spanning Tree\n";
MST.createGraph();
MST.primsAlgo();
getch();
}
Output:
Prims algorithm to find minimum spanning tree
Enter Total Nodes: 3
Enter Adjancy Matrix:
9
6
3
2
8
7
4
3
0
13
32
Result:
Thus the program for minimum spanning tree using Prim's algorithm is
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:15

SHORTEST PATH ALGORITHMS

In graph theory, the shortest path problem is the problem of finding a path
between two vertices (or nodes) in a graph such that the sum of the weights of its
constituent edges is minimized.Dijkstra's algorithm solves the single-source
shortest path problem. BellmanFord algorithm solves the single-source problem if
edge weights may be negative.FloydWarshall algorithm solves all pairs shortest
paths.
Ex: (i) Write a c++ program to find the shortest path in the graph using
Dijkstras algorithm.
Aim:
To write a c++ program to find the shortest path in the graph using
Dijkstras algorithm.
Algorithm:
Step 1: Start the program.
Step 2: Assign to every node a tentative distance value: set it to zero for our initial
node and to infinity for all other nodes.
Step 3: Mark all nodes unvisited.
Step 4: Set the initial node as current.
Step 5: Create a set of the unvisited nodes called the unvisited set consisting of all
the nodes.
Step 6: For the current node, consider all of its unvisited neighbors and calculate
their tentative distances.
Step 7: Compare the newly calculated tentative distance to the current assigned
value and assign the smaller one.
Step 8: Mark the current node as visited and remove it from the unvisited set.
Step 9: If the destination node has been marked visited or if the smallest tentative
distance among the nodes in the unvisited set is infinity then stop.
Step 10: Select the unvisited node that is marked with the smallest tentative
distance, and set it as the new "current node" then go back to step 6.
Step 11: Stop the program.
Program:
#include<iostream>
#define INFINITY 999
using namespace std;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class Dijkstra{
private:
int adjMatrix[15][15];
int predecessor[15],distance[15];
bool mark[15]; //keep track of visited node
int source;
int numOfVertices;
public:
void read();
void initialize();
while((source<0) && (source>numOfVertices-1)) {
cout<<"Source vertex should be between 0 and"<<numOfVertices-1<<endl;
cout<<"Enter the source vertex again\n";
cin>>source;
}
}
void Dijkstra::initialize(){
for(int i=0;i<numOfVertices;i++) {
mark[i] = false;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance[source]= 0;
}
int Dijkstra::getClosestUnmarkedNode(){
int minDistance = INFINITY;
int closestUnmarkedNode;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && ( minDistance >= distance[i])) {
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}
void Dijkstra::calculateDistance(){
initialize();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int minDistance = INFINITY;


int closestUnmarkedNode;
int count = 0;
while(count < numOfVertices) {
closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = true;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {
if(distance[i] >
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]) {
distance[i] =
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
}
void Dijkstra::printPath(int node){
if(node == source)
cout<<(char)(node + 97)<<"..";
else if(predecessor[node] == -1)
cout<<"No path from <<source<<to "<<(char)(node + 97)<<endl;
else {
printPath(predecessor[node]);
cout<<(char) (node + 97)<<"..";
}
}
void Dijkstra::output(){
for(int i=0;i<numOfVertices;i++) {
if(i == source)
cout<<(char)(source + 97)<<".."<<source;
else
printPath(i);
cout<<"->"<<distance[i]<<endl;
}
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int main(){
Dijkstra G;
G.read();
G.calculateDistance();
G.output();
return 0;
}
Output:
Enter the number of vertices of the graph(should be >0) 6
Enter the adjacency matrix for the graph
To enter infinity enter 999
Enter the (+ve) weights for the row 0
0 4 2 999 999 999
Enter the (+ve) weights for the row 1
4 0 1 5 999 999
Enter the (+ve) weights for the row 2
2 1 0 8 10 999
Enter the (+ve) weights for the row 3
999 5 8 0 2 6
Enter the (+ve) weights for the row 4
999 999 10 2 0 3
Enter the (+ve) weights for the row 5
999 999 999 6 3 0
Enter the source vertex 0
a..0->0
a..c..b..->3
a..c..->2
a..c..b..d..->8
a..c..b..d..e..->10
a..c..b..d..e..f..->13
Result:
Thus the program to find shortest path using Dijkstra's algorithm is executed
successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex: (ii) Write a c++ program to find the shortest path in the graph using
Floyd Warshalls algorithm.
Aim:
To write a c++ program to find the shortest path in the graph using Floyd
Warshalls algorithm.
Algorithm:
Step 1: Start the program.
Step 2: Get the value of distance matrix in a |V| |V| array.
Step3:for each vertex v, do dist[v][v] 0
Step4: for each edge (u,v), do dist[u][v] w(u,v) // the weight of the edge (u,v)
Step 5: if dist[i][j] > dist[i][k] + dist[k][j]
Step 6: then assign dist[i][j] dist[i][k] + dist[k][j]
Step 7: Repeat step 5 and 6 for all pair of vertices.
Step 8: Display the shortest distance between all pair of vertices.
Step 9: Stop the program.
Program:
#include <iostream>
#include <conio.h>
using namespace std;
void floyds(int b[][7])
{
int i, j, k;
for (k = 0; k < 7; k++)
{
for (i = 0; i < 7; i++)
{
for (j = 0; j < 7; j++)
{
if ((b[i][k] * b[k][j] != 0) && (i != j))
{
if ((b[i][k] + b[k][j] < b[i][j]) || (b[i][j] == 0))
{
b[i][j] = b[i][k] + b[k][j];
}
}
}
}
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

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


{
cout<<"\nMinimum Cost With Respect to Node:"<<i<<endl;
for (j = 0; j < 7; j++)
{
cout<<b[i][j]<<"\t";
}
}
}
int main()
{
int b[7][7];
cout<<"ENTER VALUES OF ADJACENCY MATRIX\n\n";
for (int i = 0; i < 7; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{
cin>>b[i][j];
}
}
floyds(b);
getch();
}
Output
ENTER VALUES OF ADJACENCY MATRIX
enter values for 1 row
0
3
6
0
0
0
0
enter values for 2 row
3
0
2
4

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

0
0
0
enter values for 3 row
6
2
0
1
4
2
0
enter values for 4 row
0
4
1
0
2
0
4
enter values for 5 row
0
0
4
2
0
2
1
enter values for 6 row
0
0
2
0
2
0
1
enter values for 7 row
0
0
0
4

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

1
1
0
Minimum Cost With Respect to Node:0
0
3
5
6
8
7
8
Minimum Cost With Respect to Node:1
3
0
2
3
5
4
5
Minimum Cost With Respect to Node:2
5
2
0
1
3
2
3
Minimum Cost With Respect to Node:3
6
3
1
0
2
3
3
Minimum Cost With Respect to Node:4
8
5
3
2
0
2
1
Minimum Cost With Respect to Node:5
7
4
2
3
2
0
1
Minimum Cost With Respect to Node:6
8
5
3
3
1
1
0
Result:
Thus the program to find the shortest path in the graph using Floyd
Warshalls algorithm is executed successfully.

K.L.N. COLLEGE OF ENGINEERING


POTTAPALAYAM.P.O, SIVAGANGAI -630611.

DEPARTMENT OF INFORMATION TECHNOLOGY

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

CS6311-PROGRAMMING AND DATA STRUCTURE LABORATORY II

II YEAR / III SEMESTER


2014 2015 (ODD)

PREPARED BY
Dr.G.RAMESH Professor/IT
SYLLABUS
CS6311

PROGRAMMING AND DATA STRUCTURE LABORATORY II

LTPC
0 0 3 2

OBJECTIVES:
The student should be made to:
Be familiarized with good programming design methods, particularly Top- Down
design.
Getting exposure in implementing the different data structures using C++
Appreciate recursive algorithms.
LIST OF EXPERIMENTS:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in


IMPLEMENTATION IN THE FOLLOWING TOPICS:
1. Constructors & Destructors, Copy Constructor.
2. Friend Function & Friend Class.
3. Inheritance.
4. Polymorphism & Function Overloading.
5. Virtual Functions.
6. Overload Unary & Binary Operators Both as Member Function & Non Member Function.
7. Class Templates & Function Templates.
8. Exception Handling Mechanism.
9. Standard Template Library concept.
10. File Stream classes.
11. Applications of Stack and Queue
12. Binary Search Tree
13. Tree traversal Techniques
14. Minimum Spanning Trees
15. Shortest Path Algorithms
TOTAL: 45 PERIODS
OUTCOMES:
At the end of the course, the student should be able to:
Design and implement C++ programs for manipulating stacks, queues, linked lists, trees,
and graphs.
Apply good programming design methods for program development.
Apply the different data structures for implementing solutions to practical problems.
Develop recursive programs using trees and graphs.
REFERENCE:
spoken-tutorial.org.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:
Standalone desktops with C++ compiler 30 Nos.
(or)
Server with C++ compiler supporting 30 terminals or more.

LIST OF EXPERIMENTS
EX.NO
1

NAME OF THE EXPERIMENT


a. CONSTRUCTORS
b. DESTRUCTORS
c. COPY CONSTRUCTOR

FRIEND FUNCTION

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

INHERITANCE
a. POLYMORPHISM

b. FUNCTION OVERLOADING

VIRTUAL FUNCTIONS

OPERATOR OVERLOADING
a. CLASS TEMPLATES

b. FUNCTION TEMPLATES

EXCEPTION HANDLING MECHANISM

STANDARD TEMPLATE LIBRARY

10

FILE STREAM CLASSES

11

APPLICATIONS OF STACK AND QUEUE

12

BINARY SEARCH TREE

13

TREE TRAVERSAL TECHNIQUES


MINIMUM SPANNING TREES

14

a. PRIMS ALGORITHM
b. KRUSKALS ALGORITHM
SHORTEST PATH ALGORITHMS

15

a. DIJKSTRAS ALGORITHM
b. FLOYD WARSHALLS ALGORITHM.
INTRODUCTION

OOP Concepts:
The object oriented paradigm is built on the foundation laid by the structured
programming concepts. The fundamental change in OOP is that a program is
designed aroundthe data being operated upon rather upon the operations
themselves. Data and its functions areencapsulated into a single entity.OOP
facilitates creating reusable code that can eventually save alot of work. A feature
called polymorphism permits to create multiple definitions for operatorsand
functions. Another feature called inheritance permits to derive new classes from

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

old ones.OOP introduces many new ideas and involves a different approach to
programming than theprocedural programming.
Benefits of object oriented programming:
Data security is enforced.
Inheritance saves time.
User defined data types can be easily constructed.
Inheritance emphasizes inventions of new data types.
Large complexity in the software development can be easily managed.
Basic C++ Knowledge:
C++ began its life in Bell Labs, where Bjarne Stroustrup developed the
language in the early1980s. C++ is a powerful and flexible programming language.
Thus, with minor exceptions, C++is a superset of the C Programming
language.The principal enhancement being the object oriented concept of a class.
A Class is a user defined type that encapsulates many important mechanisms.
Classes enableprogrammers to break an application up into small, manageable
pieces, or objects.
Basic concepts of Object-oriented programming:
Object:
Objects are the basic run time entities in an object-oriented system.They
may represent a person, a place, a bank account, a table of data or any item that the
Program has to handle.
Class:
The entire set of data and code of an object can be made of a user defined
data type withthe help of a class in fact Objects are variables of the type class.
Once a class has been defined, we can create any number of objects belonging to
that class. A class is thus a collection ofobjects of similar type.For example:
mango, apple, and orange are members of the class fruit.
ex:
fruit mango;
will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation:
The wrapping up of data and functions in to a single unit is known as
encapsulation.Dataencapsulation is the most striking feature of a class. The data is
not access able to the outsideworld and only those functions which are wrapped in

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

the class can access. This insulation of thedata from direct access by the program is
called data hiding.
Abstraction:
Abstraction refers to the act of representing essential features without
including thebackground details or explanations. Since the classes use the concept
of data abstraction,they areknown as abstraction data type(ADT).
Inheritance:
Inheritance is the process by which objects of one class acquire the
properties of objects ofanother class.
ex:The bird 'robin ' is a part of the class 'flying bird' which is again a part of the
class 'bird'.The concept of inheritance provides the idea of reusability.
Polymorphism:
Polymorphism is another important oop concept. Polymorphism means the
ability to takemore than one form. An operation may exhibit different instances.
The process of making anoperator to exhibit different behaviors in different
instance is known as operator overloading.
Input/output Statements:
Cout<<example;
Cin>>n;
Class definition:
Class definition has two components: the class head, the class body.
Class vector //the class head
{
// all class members
};
Ex.No:1(a)

CONSTRUCTORS

It is convenient if an object can initialize itself when it is first created,


without need to make a separate call to its member functions. C++ provides a non
static member function called as constructor that is automatically called when
object is created. After objects are created, their members can be initialized by
using constructors.
Important points to be noted while using constructors
Constructor name must be the same as that of its class name in which it belongs.
Constructors are invoked automatically when objects are created.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Constructors cannot specify return types nor return values.


Constructors cannot be declared static or const.
Constructors should have public access within the class.
Ex: (i) Write a C++ program with constructor function.
Aim:
To write a c++ program with constructor function.
Algorithm:
step1: create a maths class
step2: declared within a maths class private int variable, constructor and a
showdata function
step3: initialize a variable a to 100 within the constructor
step4: display a value with the help of showdata function
step4: within the main function create a instance of the maths class to m
step5: call a method of showdata function using m
Program:
# include<iostream.h>
class maths
{
int a;
public:
maths();
void showdata();
};
maths :: maths()
{
cout<<\n this is a constructor;
a=100;
}
void maths :: showdata()
{
cout<<\n the value of a=<<a;
}
void main ()
{
maths m;
m.showdata();
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Output:
This is a constructor
The value of a=100
Result:
Thus the c++ program for constructor function is executed successfully.
Ex: (ii) Write a c++ program to calculate prime number using constructor.
Aim:
To write a c++ program to calculate prime number using constructor.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class as Prime with data members,Member functions.
Step 3: Consider the argument constructor Prime() with integerArgument.
Step 4: To cal the function calculate() and do the following steps.
Step 5: For i=2 to a/2 do
Step 6: Check if a%i==0 then set k=0 and break.
Step 7: Else set k value as 1.
Step 8: Increment the value i as 1.
Step 9: Check whether the k value is 1 or 0.
Step 10:If it is 1 then display the value is a prime number.
Step 11:Else display the value is not prime.
Step 12:Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class prime
{
int a,k,i;
public:
prime(int x)
{
a=x;
}
void calculate()
{
k=1;
{
for(i=2;i<=a/2;i++)

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

if(a%i==0)
{
k=0;
break;
}
else
{
k=1;
}
}
}
void show()
{
if(k==1)
cout<< \n\tA is prime Number. ";
else
cout<<"\n\tA is Not prime.";
}
};
void main()
{
clrscr();
int a;
cout<<"\n\tEnter the Number:";
cin>>a;
prime obj(a);
obj.calculate();
obj.show();
getch();
}
Output:
Enter the number: 7
Given number is Prime Number
Result:
Thus the c++ program to calculate prime number using constructor is
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:1(b)

DESTRUCTORS

A destructor is a member function that is called automatically when an


object is destroyed.~class name ();Where the class name is the name of the
destructor and is preceded by a tilde (~) symbol.
Ex: Write a C++ program with destructor function.
Aim:
To write a c++ program with destructor function.
Algorithm:
step1: initialize n=0
step2: create a call class
step3: declared constructor and a destructor function within a call class
step4: display ++n value using constructor
step5: display --n value using destructor
step6: within the main function create two instances of the call class c1 and c2
Program:
#include<iostream.h>
int n=0;
class call
{
public:
call ()
{
cout<<\n constructor<<++n;
}
~call ()
{
cout<<\n destructor< --no;
}
};
main ()
{
call c1, c2;
}
Output:
constructor 1

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

constructor 2
destructor 1
destructor 0
Result:
Thus the c++ program for destructor function is executed successfully.
Ex.No:1(c)

COPY CONSTRUCTOR

The copy constructor is a constructor which creates an object by initializing


it with an object of the same class, which has been created previously. The copy
constructor is used to:
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then it is
a must to have a copy constructor.
Ex: Write a C++ program to calculate factorial of a given number using copy
constructor.
Aim:
To write a c++ program to calculate factorial of a given number using copy
constructor.
Algorithm:
Step 1: start the program.
Step 2: declare the class name as copy with data members and member functions.
Step 3: the constructor copy() with argument to assign the value.
Step 4: to cal the function calculate() do the following steps.
Step 5: for i=1 to var do
Step 6: calculate fact*i to assign to fact.
Step 7: increment the value as 1.
Step 8: return the value fact.
Step 9: print the result.
Step 10: stop the program.
Program:
#include<iostream.h>
#include<conio.h>

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class copy
{
int var,fact;
public:
copy(int temp)
{
var = temp;
}
double calculate()
{
fact=1;
for(int i=1;i<=var;i++)
{
fact = fact * i;
}
return fact;
}
};
void main()
{
clrscr();
int n;
cout<<"\n\tEnter the Number : ";
cin>>n;
copy obj(n);
copy cpy=obj;
cout<<"\n\t"<<n<<" Factorial is:"<<obj.calculate();
cout<<"\n\t"<<n<<" Factorial is:"<<cpy.calculate();
getch();
}
Output:
Enter the Number: 5
Factorial is: 120
Factorial is: 120
Result:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Thus the c++ program to calculate factorial of a given number using copy
constructor is executed successfully.

Ex.No:2

FRIEND FUNCTION

A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.A friend can be a function, function template, or member
function, or a class or class template, in which case the entire class and all of its
members are friends.
Ex: Write a C++ program to find the mean value of a given number using
friend function.
Aim:
To write a c++ program to find the mean value of a given number using
friend function.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Algorithm:
Step 1: Start the program.
Step 2: Declare the class name as Base with data members and member functions.
Step 3: The function get() is used to read the 2 inputs from the user.
Step 4: Declare the friend function mean(base ob) inside the class.
Step 5: Outside the class to define the friend function and do the following.
Step 6: Return the mean value (ob.val1+ob.val2)/2 as a float.
Step 7: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
Enter two values: 10, 20
Mean Value is: 15
Result:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Thus the c++ program to find the mean value of a given number using friend
function is executed successfully.

Ex.No:3

INHERITANCE

A class has specified data type and if you need another data type similar to
the previous onewith some additional features,instead of creating a new data type,
C++ allows inheriting themembers of the existing type and can add some more
features to the new class. This property isreferred to as inheritance.The old class is
called as base class and new class is called as derivedclass or child class.The
general form or the syntax of specifying a derived class is:
Class derivedclassname :acessspecifies baseclassname
{
//body of the derived class
}
The colon indicates that, the derived class named derivedclassname is
derived from the baseclass named baseclassname. The access specifier of the base
class must be private,protectedor public.If no accessspecifier is present is assumed
private by default. The body of the derivedclass contains member data and member
functions of its own.
Single inheritance:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

A derived class with only one base class is called as single


Inheritance.Thederived class can access all the members of the base class and can
add members of its own.
Ex: (i) Write a c++ program to display student information using Single
inheritance.
Aim:
To write a c++ program for student information system using single
inheritance.
Algorithm:
step1: Take two classess teacher and student
step2: withina teacher class Enter name and number values with the help of
getdata() function anddisplay this data using putdata() function.
step3: within the student class Enter and display marks m1,m2,m3 with the help of
getdata(),putdata() functions.
step4: within the student class extends teacher class and using data and their
functions to thestudent class
Program:
#include<iostream.h>
class teacher
{
private:
char name[25];
long number;
public:
void getdata()
{
cout<<\n \t Enter your name:;
cin>>name;
cout<<\n \t Enter your number:;
cin>>number;
}
void putdata()
{
cout<<\n \t name:<<name;
cout<<\n \t number : <<number;
}
};

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class student : public teacher


{
private:
int m1,m2,m3;
public:
void getdata()
{
teacher :: getdata();
cout<<\n \t Enter marks in three subjects:;
cin>>m1>>m2>>m3;
}
void putdata()
{
teacher :: putdata();
cout<<\n \t Marks of three subjects:<<m1<<m2<<m3;
}
};
void main()
{
student s1,s2;
cout<<\n Enter data for student 1:\n:
s1.getdata();
cout<<\n Enter data for student2 :\n;l
s2.getdata();
cout<<\n the data of student 1:;
s1.putdata();
cout<<\n the data of student 2:;
s2.putdata();
}
Output:
Enter data for student1
Enter your name:James
Enter your number:1
Enter 3 subject mark:75 65 85
Enter data for student 2
Enter your name :Susila
Enter your number:2
Enter marks in 3 subjects:65 85 75
The data for student 1

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Name:James
Number:1
Marks of three subjects:75 65 85
The data for student 2
Name :Susila
Number :2
Marks of three subjects:65 85 75
Result:
Thus the c++ program to display student information using Single
inheritanceis executed successfully.
Ex: (ii) Write a c++ program to find out the payroll system using single
inheritance.
Aim:
To write a c++ program to find out the payroll system using single
inheritance.
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class emp.
Step 3: Define and declare the function get() to get the employee details.
Step 4: Declare the derived class salary.
Step 5: Declare and define the function get1() to get the salary details.
Step 6: Define the function calculate() to find the net pay.
Step 7: Define the function display().
Step 8: Create the derived class object.
Step 9: Read the number of employees.
Step 10: Call the function get(),get1() and calculate() to each employees.
Step 11: Call the display().
Step 12: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class emp
{
public:
int eno;
char name[20],des[20];

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

void get()
{
cout<<"Enter the employee number:";
cin>>eno;
cout<<"Enter the employee name:";
cin>>name;
cout<<"Enter the designation:";
cin>>des;
}
};
class salary:public emp
{
float bp,hra,da,pf,np;
public:
void get1()
{
cout<<"Enter the basic pay:";
cin>>bp;
cout<<"Enter the Humen Resource Allowance:";
cin>>hra;
cout<<"Enter the Dearness Allowance :";
cin>>da;
cout<<"Enter the Profitablity Fund:";
cin>>pf;
}
void calculate()
{
np=bp+hra+da-pf;
}
void display()
{
cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t"<<
pf<<"\t"<<np<<"\n";
}
};
void main()
{
int i,n;
char ch;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

salary s[10];
clrscr();
cout<<"Enter the number of employee:";
cin>>n;
for(i=0;i<n;i++)
{
s[i].get();
s[i].get1();
s[i].calculate();
}
cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for(i=0;i<n;i++)
{
s[i].display();
}
getch();
}
Output:
Enter the Number of employee:1
Enter the employee No: 150
Enter the employee Name: ram
Enter the designation: Manager
Enter the basic pay: 5000
Enter the HR allowance: 1000
Enter the Dearness allowance: 500
Enter the profitability Fund: 300
E.No E.name des
BP HRA DA PF
150 ram
Manager 5000 1000 500 300

NP
6200

Result:
Thus the c++ program to find out the payroll system using single
inheritanceis executed successfully.
Multiple Inheritances:
Very often situations may arise in which a class has to derive featuresfrom
more than one class. Multiple inheritancesfacilitate a class to inherit features from
morethan one class. The derived class can access two or more classes and can add
properties of itsown.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex: (iii) Write a program for employee database using multiple inheritances.
Aim:
To write a c++ program for employee database using multiple inheritance.
Algorithm:
step1:Take three classess student,employee,manager
step2:withina student class Enter name and school, college data with the help of
getdata()function and display this data using putdata() function.
step3:within the employee class Enter and display company, age data with the help
ofgetdata(),putdata() functions.
step4:within the manager class extends student and employee classess and using
data and theirfunctions to the manager class and Enter & display disegnation
,salary of the manager usingputdata(),getdata() functions
step5:within the main function create instance of manager class m and call
getdata() andputdata() functions.
Program:
#include<iostream.h>
#include<conio.h>
const int max=50;
class student
{
private:
char name[max];
char school[max];
char college[max];
public:
void getdata()
{
cout<<\n \t enter name :;
cin>>name;
cout<<\t enter school name:;
cin>school;
cout<<\n \t enter college name:;
cin>>college;
}
void putdata()
{
cout<<\n \t name :<<name;
cout<<\n \t school name :<<school;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<\n \t college name :<<college;


}
};
class employee
{
private
char company[max];
int age;
public :
void getdata()
{
cout<<\n \t enter the company name :;
cin>>company;
cout<<\n \t enter age:;
cin>>age;
}
void putdata()
{
cout<<\n \t company name :<<company;
cout<<\t age:<<age;
}
};
class manager : private employee,private student
{
private:
char design[max];
float salary;
public :
void getdata()
{
student ::getdata();
employee ::getdata();
cout<<\n \t enter your designation :;
cin>>design;
cout<<\n \t enter salary:;
cin>>salary;
}
void putdata()
{
student ::putdata();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

employee::putdata();
cout<<\n \t designation :<<design;
cout<<\n \t salary :<<salary;
}
};
void main(0
{
manager m;
clrscr();
cout<<\n enter data for manager:<<endl;
m.gatdata();
cout<<\n the data for manager is :<<endl;
m.putdata();
}
Output:
Enter data for manager :
Enter name : Ram
Enter name of school: GMSS
Enter name of college :GCET
Enter name of company :CMC
Enter age :24
Enter designation :Analyst
Enter salary :10000
The data for manager is
Student Name :Ram
School Name :GMSS
College Name :GCET
Company Name :CMC
Age :24
Designation :Analyst
Salary:10000
Result:
Thus the c++ program for employee database using multiple inheritancesis
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:4(a)

POLYMORPHISM

The word polymorphism means having many forms. Typically,


polymorphism occurs when there is a hierarchy of classes and they are related by
inheritance.C++ polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that invokes the
function.
Ex: Write a c++ program to explain the concept of polymorphism.
Aim:
To write a c++ program for polymorphism.
Program:
#include <iostream>
using namespace std;
class Shape
{
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
virtual int area()

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

return 0;
}
Output:
Rectangleclass area
Triangleclass area
Result:
Thus the c++ program for polymorphism is executed successfully.

Ex.No:4(b)

FUNCTION OVERLOADING

C++ enables two or more functions with same name but with different types
of arguments orwith different number of arguments .This capability to overload a
function is called functionoverloading.
Ex: (i) Write a c++ program to explain function overloading with different
number of arguments.
Aim:
To write a c++ program to explain function overloading with different
number of arguments.
Algorithm:
step1:create two functions with the same name and same data type but different
number of
arguments
step2: within the main function initialize integer values x=5,y=10,z=20,a=0,b=0
step3:a)s=call sum(x,y)
print s
b) s=call sum(x,y,z)
prin ts
step4:a)with in the called function of sum(x,y)
return x+y
b)with in the called function of sum(x,y,z)
return x+y+z
Program:
#include<iostream.h>

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

#include<conio.h>
int sum(int, int);
int sum(int, int, int)
void main()
{
int x=5,y=10,z=20,a=0,b=0;
clrscr();
a=sum(x,y);
b=sum(x,y,z);
cout<< sum of two integers=<<a<<endl;
cout<<sum of three integers=<<b<<endl;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
Output:
sum of two intezers=15
sum of three integers=35
Result:
Thus the c++ program for function overloading with different number of
argumentsis executed successfully.
Ex: (ii) Write a c++ program to explain function overloading with type, order,
and sequence of arguments.
Aim:
To write a c++ program to explain function overloading with type, order,
and sequence of arguments.
Algorithm:
step1: create more functions with the same name and different data types and
different number of arguments
step2: within the main function initialize different data type variables

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

step3:a)sum=call all functions print sum


step4:a)write all called functions return sum of values
Program:
#include<iostream.h>
#include<conio.h>
int sum(int,int);
int sum(int,int,int);
float sum(float,int,float);
double sum(double,float);
double sum(int,float,double);
long double sum(long double,double);
void main()
{
int a=sum(4,6);
int b=sum(2,4,6);
float c=sum(3.5f,7,5.6f);
double d=sum(7,8,1.2f);
double e=sum(1,2.2f,8.6);
long double f=sum(100,80);
clrscr();
cout<<sum(int,int) =<<a<<endl;
cout<< sum(int,int,int) =<<b<<endl;
cout<<sum(float,int,float) =<<c<<endl;
cout<< sum(double,float) =<<d<<endl;
cout<< sum(int,float,double) =<<e<<endl;\
cout<<sum(long double,double) = <<f;
getch();
}
int sum(int x,int y)
{
return(x+y);
}
int sum(int x,int y,int z)
{
return(x+y+z);
}
float sum(float x,int y,float z)
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

return(x+y+z);
}
double sum(double x,float y)
{
return(x+y);
}
double sum(int x,float y,double z)
{
return(x+y);
}
long double sum(long double x,double y)
{
return(x+y);
}
Output:
sum(int,int) =10
sum(int,int,int) =12
sum(float,int,float) =16.1
sum(double,float) =9
sum(int,float,double) =11.8
sum(long,double,double) =180
Result:
Thus the c++ program for function overloading with type, order, and
sequence of argumentsis executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No: 5

VIRTUAL FUNCTIONS

Virtual means existing in effect but not in reality. A virtual function is one
that does notreally exist but nevertheless appears real to some parts of program.
Virtual functions provide away for a program to decide, when it is running, what
function to call. Virtual function allowsgreater flexibility in performing the same
kinds of action, on different kind of objects.
While using virtual functions:
It should be a member function of a class.
Static member functions cannot be virtual functions.
A virtual function should be declared in the base class specifications.
A virtual function may or may not have function body.
Virtual functions can be overloaded.
Constructors cannot be declared as virtual functions.
There can be virtual destructors.
Ex: Write a program to explain virtual functions.
Aim:
To write a c++ program for virtual function.
Algorithm:
Step 1: Start the program.
Step 2: Declare the base class base.
Step 3: Declare and define the virtual function show().
Step 4: Declare and define the function display().
Step 5: Create the derived class from the base class.
Step 6: Declare and define the functions display() and show().
Step 7: Create the base class object and pointer variable.
Step 8: Call the functions display() and show() using the base class object and
pointer.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 9: Create the derived class object and call the functions display() and show()
using the derived class object and pointer.
Step 10: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n Base class show:";
}
void display()
{
cout<<"\n Base class display:" ;
}
};
class drive:public base
{
public:
void display()
{
cout<<"\n Drive class display:";
}
void show()
{
cout<<"\n Drive class show:";
}
};
void main()
{
clrscr();
base obj1;
base *p;
cout<<"\n\t P points to base:\n" ;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

p=&obj1;
p->display();
p->show();
cout<<"\n\n\t P points to drive:\n";
drive obj2;
p=&obj2;
p->display();
p->show();
getch();
}
Output:
P points to Base
Base class display
Base class show
P points to Drive
Base class Display
Drive class Show
Result:
Thus the c++ program for virtual function is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:6

OPERATOR OVERLOADING

We know that operator is a symbol that performs some operations on one or


more operands. The ability to overload operators is one of the C++s most
powerful features++ allowsus to provide new definitions to some built in
operators. We can give several meaning to anoperator, depending upon the types of
arguments used. This capability to overload an operator iscalled operator
overloading.Operators are overloaded by creating operator functions.An operator
function consists of a function definition, similar to a normal function except that
the function name nowbecomes the keyword OPERATOR followed by the symbol
being overloaded. The general formor syntax of an operator function is:
Return type class name:: operator <operator symbol>(argument list)
{
//Body of the function
}
Where return type is the data type of the value return after the specific
operation, operatorsymbol is the operator being overloaded, that is preceded by the
keyword operator, and Operatorfunction is usually a member function or a friend
function.An operator that deals with only one operand is called as a unary operator.
Some of thecommonly used unary operators are ++,--,!,~ and unary
minus.Overloading increment and decrement operators: The increment operator
(++) and the decrementoperator ( _ _ ) are unary operators since they act on only
one operand. Both the increment anddecrement operators have two forms. They are
prefix(i.e do the operation and then use thecontent of the variable.) and postfix (i.e
use the content of the variable and then do theoperation)notation. The general
syntax form or the syntax of the prefix and postfix operatorfunctions are
//prefix increment
return type operator++()
{
// Body of the prefix operator
}
//postfix increment

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Return operator++(int x)
{
//body of the postfix operator
}

Ex: (i) Write a program to find the complex numbers using unary operator
overloading.
Aim:
To write a program to find the complex numbers using unary operator
overloading.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator ++ to increment the values
Step 6: Define the function operator - -to decrement the values.
Step 7: Define the display function.
Step 8: Declare the class object.
Step 9: Call the function getvalue
Step 10: Call the function operator ++() by incrementing the class object and call
the function display.
Step 11: Call the function operator - -() by decrementing the class object and call
the function display.
Step 12: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b,c;
public:
complex(){}
void getvalue()
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"Enter the Two Numbers:";


cin>>a>>b;
}
void operator++()
{
a=++a;
b=++b;
}
void operator--()
{
a=--a;
b=--b;
}
void display()
{
cout<<a<<"+\t"<<b<<"i"<<endl;
}
};
void main()
{
clrscr();
complex obj;
obj.getvalue();
obj++;
cout<<"Increment Complex Number\n";
obj.display();
obj--;
cout<<"Decrement Complex Number\n";
obj.display();
getch();
}
Output:
Enter the two numbers: 3 6
Increment Complex Number
4+
7i

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Decrement Complex Number


3+
6i
Result:
Thus the c++ programto find the complex numbers using unary
operator overloading is executed successfully.
Ex: (ii) Write a program to add two complex numbers using binary operator
overloading.
Aim:
To write a program to add two complex numbers using binary operator
overloading.
Algorithm:
Step 1: Start the program.
Step 2: Declare the class.
Step 3: Declare the variables and its member function.
Step 4: Using the function getvalue() to get the two numbers.
Step 5: Define the function operator +() to add two complex numbers.
Step 6: Define the function operator ()to subtract two complex numbers.
Step 7: Define the display function.
Step 8: Declare the class objects obj1,obj2 and result.
Step 9: Call the function getvalue using obj1 and obj2
Step 10: Calculate the value for the object result by calling the function operator +
and operator -.
Step 11: Call the display function using obj1 and obj2 and result.
Step 12: Return the values.
Step 13: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;
public:
void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cin>>a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a=a+ob.a;
t.b=b+ob.b;
return(t);
}
complex operator-(complex ob)
{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};
void main()
{
clrscr();
complex obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:\n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

getch();
}
Output:
Enter the value of Complex Numbers a, b
4
5
Enter the value of Complex Numbers a, b
2
2
Input Values
4 + 5i
2 + 2i
Result
6 + 7i
2 + 3i
Result:
Thus the c++ programto add two complex numbers using binary
operator overloading is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:7(a)

FUNCTION TEMPLATES

Templates are the foundation of generic programming, which


involveswriting code in a way that is independent of any particular type.A template
is a blueprint or formula for creating a generic class or a function. The library
ontainers like iterators and algorithms are examples of generic programming and
have been developed using template concept.There is a single definition of each
container, such as vector, but we can define many different kinds of vectors for
example, vector <int> or vector <string>.You can use templates to define
functions as well as classes.The general form of a template function definition is
template <class type> ret-type func-name(parameter list)
{
// body of function
}
Ex: Write a c++ program to swap the numbers using function template.
Aim:
To swap the numbers using the concept of function template.
Algorithm:
Step 1: start the program.
Step 2: declare the template class.
Step 3: declare and define the functions to swap the values.
Step 4: declare and define the functions to get the values.
Step 5: read the values and call the corresponding functions.
Step6: display the results.
Step 7: stop the program.
Program:
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp=x;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"\na and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\na and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\nc and d after swaping :"<<c<<"\t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"enter a,b values(integer):";
cin>>a>>b;
cout<<"enter c,d values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
Output:
enter a, b values (integer): 10 20
enter c, d values (float): 2.50 10.80
a and b before swapping: 10 20
a and b after swapping: 20 10
c and d before swapping: 2.50 10.80
c and d after swapping: 10.80 2.50
Result:
Thus the c++ program to swap the numbers using function templateis
executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:7(b)

CLASS TEMPLATES

Just like we can create function templates, we can also create class
templates, allowing classes to have members that use template parameters as types.
Ex: Write a c++ program to find the greater of two numbers using class
template.
Aim:
To write a c++ program to find the greater of two numbers using class
template.
Algorithm:
Step 1: start the program.
Step 2: declare the template class.
Step 3: declare and define the functions to swap the values.
Step 4: declare and define the functions to get the values.
Step 5: read the values and call the corresponding functions.
Step6: display the results.
Step 7: stop the program.
Program:
#include <iostream>
using namespace std;
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

retval = a>b? a : b;
return retval;
}
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
Output:
100
Result:
Thus the c++ program to find the greater of two numbers using class
templateis executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:8

EXCEPTION HANDLING MECHANISM

An exception is a problem that arises during the execution of a program. A


C++ exception is a response to an exceptional circumstance that arises while a
program is running, such as an attempt to divide by zero.Exceptions provide a way
to transfer control from one part of a program to another. C++ exception handling
is built upon three keywords: try, catch, and throw.
throw: A program throws an exception when a problem shows up. This is done
using a throwkeyword.
catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
Assuming a block will raise an exception, a method catches an exception
using a combination of thetry and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is
referred to as protected code, and the syntax for using try/catch looks like the
following:
try
{
// protected code
}catch(ExceptionName e1 )
{
// catch block
}catch(ExceptionName e2 )
{
// catch block
}catch(ExceptionName eN )
{
// catch block
}
Ex: Write a c++ program to perform exception handling for divide by zero
exception.
Aim:
To perform exception handling for Divide by zero Exception.
Algorithm:
Step 1: Start the program.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 2: Declare the variables a,b,c.


Step 3: Read the values a,b,c,.
Step 4: Inside the try block check the condition.
a. if(a-b!=0) then calculate the value of d and display.
b. otherwise throw the exception.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.
Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
float d;
clrscr();
cout<<"Enter the value of a:";
cin>>a;
cout<<"Enter the value of b:";
cin>>b;
cout<<"Enter the value of c:";
cin>>c;
try
{
if((a-b)!=0)
{
d=c/(a-b);
cout<<"Result is:"<<d;
}
else
{
throw(a-b);
}
}
catch(int i)
{
cout<<"Answer is infinite because a-b is:"<<i;
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

getch();
}
Output:
Enter the value for a: 20
Enter the value for b: 20
Enter the value for c: 40
Answer is infinite because a-b is: 0
Result:
Thus the c++ program for exception handling for Divide by zero Exceptionis
executed successfully.

Ex.No:9

STANDARD TEMPLATE LIBRARY

The C++ STL (Standard Template Library) is a powerful set of C++


template classes to provide general-purpose templatized classes and functions that

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

implement many popular and commonly used algorithms and data structures like
vectors, lists, queues, and stacks.
At the core of the C++ Standard Template Library is following three wellstructured components:
Component

Description

Containers

Containers are used to manage collections of objects of a certain kind.


There are several different types of containers like deque, list, vector,
map etc.

Algorithms

Algorithms act on containers. They provide the means by which you


will perform initialization, sorting, searching, and transforming of the
contents of containers.

Iterators

Iterators are used to step through the elements of collections of


objects. These collections may be containers or subsets of containers.

Ex: Write a c++ program to demonstrate the standard template library using
vector container.
Aim:
To write a c++ program to demonstrates the standard template library
(vector container).
Algorithm:
Step 1: Start the program.
Step 2: create a vector to store int.
Step 3: display the original size of vec.
Step 4: push 5 values into the vector.
Step 5: display extended size of vec.
Step 6: access 5 values from the vector.
Step 7: use iterator to access the values.
Step 8: Stop the program.
Program:
#include<iostream>
#include<vector>
usingnamespace std;
int main()
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

// create a vector to store int


vector<int> vec;
int i;
// display the original size of vec
cout <<"vector size = "<< vec.size()<< endl;
// push 5 values into the vector
for(i =0; i <5; i++){
vec.push_back(i);
}
// display extended size of vec
cout <<"extended vector size = "<< vec.size()<< endl;
// access 5 values from the vector
for(i =0; i <5; i++){
cout <<"value of vec ["<< i <<"] = "<< vec[i]<< endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()){
cout <<"value of v = "<<*v << endl;
v++;
}
return0;
}
Output:
vector size =0
extended vector size =5
value of vec [0]=0
value of vec [1]=1
value of vec [2]=2
value of vec [3]=3
value of vec [4]=4
value of v =0
value of v =1
value of v =2
value of v =3
value of v =4
Result:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Thus the c++ program for standard template library (vector container)is
executed successfully.

Ex.No:10

FILE STREAM CLASSES

File stream classes includes the operations opening and closing a file, read
from a file and write into the file. This requires a standard c++ library
called fstream, which defines three new data types:
Data Type
Description
ofstream

This data type represents the output file stream and is used to create files
and to write information to files.

ifstream

This data type represents the input file stream and is used to read
information from files.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

fstream

This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can create files,
write information to files, and read information from files.

Ex: Write a c++ program for read & write file operation to convert lowercase
to uppercase.
Aim:
To write a c++ program for read & write file operation to convert lowercase
to uppercase.
Algorithm:
Step 1: start the program.
Step 2: declare the variables.
Step 3: read the file name.
Step 4: open the file to write the contents.
Step 5: writing the file contents up to reach a particular condition.
Step6: write the file contents as uppercase.
Step7: open the file to read the contents.
Step 8: Stop the program.
Program:
#include<fstream.h>
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<iostream.h>
#include<conio.h>
void main()
{
char c,u;
char fname[10];
clrscr();
ofstream out;
cout<<"Enter File Name:";
cin>>fname;
out.open(fname);
cout<<"Enter the text(Enter # at end)\n"; //write contents to file
while((c=getchar())!='#')

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
u=c-32;
out<<u;
}
out.close();
ifstream in(fname);
//read the contents of file
cout<<"\n\n\t\tThe File contains\n\n";
while(in.eof()==0)
{
in.get(c);
cout<<c;
}
getch();
}
Output:
Enter File Name: two.txt
Enter contents to store in file (enter # at end)
oops programming
The File Contains
OOPS PROGRAMMING
Result:
Thus the c++ program for read & write file operation to convert lowercase to
uppercaseis executed successfully.
Ex.No:11

APPLICATIONS OF STACK AND QUEUE

A stack is a basic data structure that can be logically thought as linear


structure represented by a real physical stack or pile, a structure where insertion
and deletion of items takes place at one end called top of the stack where as in
queue insertion and deletion of items takes place at front and rear.
Ex:(i) Write a c++ program to convert infix expression into postfix expression.
Aim:
To write a c++ program to convert infix expression into postfix expression.
Algorithm:
Step 1: Read an character input

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Step 2: Actions to be performed at end of each input


Step 2.1:Opening brackets - Push into stack and then Go to step (1)
Step 2.2: Number - Print and then Go to step (1)
Step 2.3: Operator - Push into stack and then Go to step (1)
Step 2.4:Closing brackets - Pop it from the stack
Step2.4.1: If it is an operator, print it, Go to step (1)
Step2.4.2: If the popped element is an opening bracket,discard it and go to step (1)
Step 2.5: New line character - STOP
Program:
#include<iostream>
#include<vector>
#include<stack>
usingnamespace std;
staticint precedence(char x)//check precedence of operators
{
if(x=='(')
return0;
elseif(x=='+'||x=='-')
return1;
elseif(x=='*'||x=='/'||x=='%')
return2;
return3;
}
std::string infix_to_postfix(const std::string& infix)
{
std::stack<char> s;
std::string postfix;
for(auto ch : infix)
{
if(isalnum(ch))
postfix.push_back(ch);
elseif(ch =='(')
s.push(ch);
elseif(ch ==')')
{
while(!s.empty())
{

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

ch = s.top();
s.pop();
if(ch =='(')
break;
postfix.push_back(ch);
}
}
else
{
while(!s.empty()&& precedence(ch)<=precedence(s.top()))
{
postfix.push_back(s.top());
s.pop();
}
s.push(ch);
}
}
while(!s.empty())
{
postfix.push_back(s.top());
s.pop();
}
return postfix;
}
int main()
{
constchar infix[]="(((8 + 1) - (7 - 4)) / (11 - 9))";
cout <<"\nThe equivalent postfix expression is: "<< infix_to_postfix(infix);
return0;
}
Output:
The equivalent postfix expression is:8 1 + 7 4 - - 11 9 - /
Result:
Thus the program for infix to postfix expression conversion is executed
successfully.
Ex: (ii) Write a c++ program to evaluate an expression using Stack
Aim:

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

To write a c++ program to evaluate an expression using Stack.


Algorithm:
Step 1: Start the program.
Step 2: Read a character input.
Step 3: If the character input is a number push it into a stack.
Step 4: If the character input is a symbol pop the top two numbers and perform the
corresponding operation and push it back to the stack.
Step 5: Repeat step 3 and 4 for all the input characters.
Step 6: Stop the program.
Program:
#include <iostream>
#include <conio.h>
#include <string.h>
usingnamespace std;
struct node
{
int data;
node *next;
}*p =NULL, *top =NULL, *save =NULL, *ptr;
void push(int x)
{
p =new node;
p->data = x;
p->next =NULL;
if(top ==NULL)
{
top = p;
}
else
{
save = top;
top = p;
p->next = save;
}
}
char pop()
{
if(top ==NULL)

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

{
cout<<"underflow!!";
}
else
{
ptr = top;
top = top->next;
return(ptr->data);
delete ptr;
}
}
int main()
{
char x[30];
int a, b;
cout<<"enter the balanced expression\n";
cin>>x;
for(int i =0; i <strlen(x); i++)
{
if(x[i]>=48&& x[i]<=57)
push(x[i]-'0');
elseif(x[i]>=42&& x[i]<=47)
{
a=pop();
b=pop();
switch(x[i])
{
case'+':
push(a+b);
break;
case'-':
push(a-b);
break;
case'*':
push(a*b);
break;
case'/':
push(a/b);
break;
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
}
cout<<"ans is "<<pop()<<endl;
getch();
}
Output:
enter the balanced expression
567+8-/
ans is -1
Result:
Thus the program to evaluate an expression using Stack is executed
successfully.

Ex.No:12

BINARY SEARCH TREE

A binary search tree is a tree where each node has a left and right child.
Either child, or both children, may be missing. Assuming k represents the value of
a given node, and then a binary search tree also has the following property: all
children to the left of the node have values smaller than k, and all children to the
right of the node have values larger than k. The top of a tree is known as the root,
and the exposed nodes at the bottom are known as leaves.The height of a tree is the
length of the longest path from root to leaf.
Ex: Write a C++ program to perform the following operations in a binary
search tree:a) Insert an elementb) Delete an element c) Search for a key
element d) Find smallest node e) Find largest node f) Determine height g) Find
total nodes.
Aim:
To write a c++ program to perform the following operations in a binary
search tree: a) Insert an element b) Delete an element c) Search for a key element
d) Find smallest node e) Find largest node f) Determine height g) Find total nodes.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Algorithm:
Step 1: Start the program.
Step 2: Include necessary header files.
Step 3: Create a structure for the input data, left and right nodes.
Step 4: If the tree is null create a node and insert the data.
Step 5: Make the left and right sub tree as null.
Step 6: If the tree is not null check the item with a root node.
Step 7: If it is lesser insert it in the left sub tree else insert it in the right sub tree.
Step 8: For deleting check the item with a root node
Step 9: If it is lesser check it in the left sub tree else check it in the right sub tree
and delete the item.
Step 10: The left leaf node is the smallest node and the right leaf node is a largest
node.
Step 11: The total number of nodes are calculated using the function totalnode.
Step 12: Height of the tree determines the levels of the tree.
Step 13:Stop the program.
Program:
#include <iostream.h>
#include <process.h>//for exit(1)
#include <conio.h>
struct node{
int data;
struct node *left;
struct node *right;
};
class BST{
public:
node *tree;
BST(){
tree=NULL;
}
void createTree(node **,int item); //For Building Tree
void determineHeight(node *,int *);
int totalNodes(node *);
node **searchElement(node **,int);
void findSmallestNode(node *);
void findLargestNode(node *);
void deleteNode(int);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

};
//it is used for inserting a single element in//a tree, but if calls more than once will
create tree.
void BST :: createTree(node **tree,int item){
if(*tree == NULL){
*tree = new node;
(*tree)->data = item;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
else{
if( (*tree)->data > item)
createTree( &((*tree)->left),item);
else
createTree( &((*tree)->right),item);
}
}
void BST :: determineHeight(node *tree, int *height){
int left_height, right_height;
if( tree == NULL)
*height = 0;
else{
determineHeight(tree->left, &left_height);
determineHeight(tree->right, &right_height);
if( left_height > right_height)
*height = left_height + 1;
else
*height = right_height + 1;
}
}
int BST :: totalNodes(node *tree){
if( tree == NULL)
return 0;
elsereturn( totalNodes(tree->left) + totalNodes(tree->right) + 1 );
}
node ** BST :: searchElement(node **tree, int item){

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

if( ((*tree)->data == item) || ( (*tree) == NULL) )


return tree;
elseif( item < (*tree)->data)
return searchElement( &(*tree)->left, item);
elsereturn searchElement( &(*tree)->right, item);
}
void BST :: findSmallestNode(node *tree){
if( tree==NULL || tree->left==NULL)
cout<< tree->data;
else
findSmallestNode( tree->left);
}
void BST :: findLargestNode(node *tree){
if( tree==NULL || tree->right==NULL)
cout<<tree->data;
else
findLargestNode(tree->right);
}
void BST :: deleteNode(int item){
node *curr=tree,*succ,*pred;
int flag=0,delcase;
//step to find location of node
while(curr!=NULL && flag!=1)
{
if(item < curr->data){
pred = curr;
curr = curr->left;
}
elseif(item > curr->data){
pred = curr;
curr = curr->right;
}
else{ //curr->data = item
flag=1;
}
}

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

if(flag==0){
cout<<"\nItem does not exist : No deletion\n";
getch();
goto end;
}
//Decide the case of deletion
if(curr->left==NULL && curr->right==NULL)
delcase=1; //Node has no childelse
if(curr->left!=NULL && curr->right!=NULL)
delcase=3; //Node contains both the childelse
delcase=2; //Node contains only one child
//Deletion Case 1
if(delcase==1){
if(pred->left == curr) //if the node is a left child
pred->left=NULL; //set pointer of its parentelse
pred->right=NULL;
delete(curr); //Return deleted node to the memory bank.
}
//Deletion Case 2
if(delcase==2){
if(pred->left==curr){ //if the node is a left childif(curr->left==NULL)
pred->left=curr->right;
else
pred->left=curr->left;
}
else{ //pred->right=currif(curr->left==NULL)
pred->right=curr->right;
else
pred->right=curr->left;
}
delete(curr);
}
//Deletion case 3
if(delcase==3){
succ = find_Insucc(curr); //Find the in_order successor//of the node.int item1
= succ->data;
deleteNode(item1); //Delete the inorder successor

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

curr->data = item1; //Replace the data with the data of//in order successor.
}
end:
}
void main(){
BST obj;
int choice;
int height=0,total=0,n,item;
node **tmp;
while(1){
clrscr();
cout<<"*****BINARY SEARCH TREE OPERATIONS*****\n\n";
cout<<"1) Create Tree\n";
cout<<"2) Insert Node\n";
cout<<"3) Delete Node\n";
cout<<"4) Height of Tree\n";
cout<<"5) Total Nodes\n";
cout<<"6) Search Node\n";
cout<<"7) Find Smallest Node\n";
cout<<"8) Find Largest Node\n";
cout<<"9) Exit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1 : //Create Tree
cout<<"\n\n--Creating Tree--";
cout<<"\nHow many nodes u want to enter : ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"Enter value : ";
cin>>item;
obj.createTree(&obj.tree,item);
}
break;
case 2 : //Inserting a node in a tree
cout<<"\n\n--Inserting Node in a tree--\n";

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"Enter value : ";


cin>>item;
obj.createTree(&obj.tree,item);
cout<<"\nItem is inserted\n";
getch();
break;
case 3 : //Deleting a node from a tree
cout<<"\n\n--Deleting a Node from a tree--\n";
cout<<"Enter value : ";
cin>>item;
obj.deleteNode(item);
break;
case 4 : //Determining Height of Tree
obj.determineHeight(obj.tree,&height);
cout<<"\n\nHeight of Tree : "<<height;
getch();
break;
case 5 : //Total nodes in a tree
total=obj.totalNodes(obj.tree);
cout<<"\n\nTotal Nodes : "<<total;
getch();
break;
case 6 : //Search element
cout<<"\n\n--Search Element--\n";
cout<<"Enter item to searched : ";
cin>>item;
&(*tmp) = obj.searchElement(&obj.tree,item);
if( (*tmp) == NULL)
cout<<"\nSearch Element Not Found";
else
cout<<"\nSearch Element was Found";
getch();
break;
case 7 : //Find Smallest Node
cout<<"\n\nSmallest Node is : ";
obj.findSmallestNode(obj.tree);

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

getch();
break;
case 8 : //Find Largest Node
cout<<"\n\nLargest Node is : ";
obj.findLargestNode(obj.tree);
getch();
break;
case 9 :
exit(1);
}//end of switch
}
}
Output:
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 1
--Creating Tree
How many nodes u want to enter : 4
Enter value : 12
Enter value : 34
Enter value : 45
Enter value : 67
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

7) Find Smallest Node


8) Find Largest Node
9) Exit
Enter your choice : 5
Total Nodes: 4
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 6
--Search Element-Enter item to searched : 10
Search Element Not Found
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 6
--Search Element-Enter item to searched : 12
Element was Found
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 7
Smallest node is: 12
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 8
Largest node is: 67
*****BINARY SEARCH TREE OPERATIONS*****
1) Create Tree
2) Insert Node
3) Delete Node
4) Height of Tree
5) Total Nodes
6) Search Node
7) Find Smallest Node
8) Find Largest Node
9) Exit
Enter your choice : 9
Result:
Thus the program for binary search tree operations is executed successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:13

TREE TRAVERSAL TECHNIQUES

Ex: Write a C++ program to traverse the given binary tree in a)preorder b)inorder
c)post order
Aim:
To write a C++ program to traverse the given binary tree in a)preorder
b)inorder c)post order.
Algorithm:
Step 1: Start the program.
Step 2: Include necessary header files.
Step 3: Create a structure for the input data, left and right nodes.
Step 4: If the tree is null create a node and insert the data.
Step 5: Make the left and right sub tree as null.
Step 6: If the tree is not null check the item with a root node.
Step 7: If it is lesser insert it in the left sub tree else insert it in the right sub tree.
Step 8: In-order: traverse left first then root then right nodes.
Step 7:Preorder: traverse root first then left then right nodes.
Step 7:Post-order: traverse left first then right then root nodes.
Step 7: Stop the program.
Program:
#include <iostream.h>
#include <process.h>//for exit(1)
#include <conio.h>
struct node{
int data;
struct node *left;
struct node *right;
};

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

class BST{
public:
node *tree;
BST(){
tree=NULL;
}
void createTree(node **,int item); //For Building Tree
void preOrder(node *); //For Tree Traversal
void inOrder(node *);
void postOrder(node *);
//it is used for insertinga single element in a tree, but if calls more than once will
create tree.
void BST :: createTree(node **tree,int item){
if(*tree == NULL){
*tree = new node;
(*tree)->data = item;
(*tree)->left = NULL;
(*tree)->right = NULL;
}
else{
if( (*(tree)->data > item)
createTree( &((*tree)->left),item);
else
createTree( &((*tree)->right),item);
}
}
void BST :: preOrder(node *tree){
if( tree!=NULL){
cout<<" "<< tree->data;
preOrder(tree->left);
preOrder(tree->right);
}
}
void BST :: inOrder(node *tree){
if( tree!=NULL){
inOrder( tree->left);
cout<<" "<< tree->data;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

inOrder(tree->right);
}
}
void BST :: postOrder(node *tree){
if( tree!=NULL){
postOrder( tree->left);
postOrder( tree->right);
cout<<" "<<tree->data;
}
}
void main(){
BST obj;
int choice;
node **tmp;
while(1){
clrscr();
cout<<"Tree Traversal\n";
cout<<"1) Create Tree\n";
cout<<"2) Inorder Traversal \n";
cout<<"3) Preorder Traversal \n";
cout<<"4) Postorder Traversal \n";
cout<<"5) Exit\n";
cout<<"Enter your choice : ";
cin>>choice;
switch(choice){
case 1 : //Create Tree
cout<<"\n\n--Creating Tree--";
cout<<"\nHow many nodes u want to enter : ";
cin>>n;
for(int i=0;i<n;i++){
cout<<"Enter value : ";
cin>>item;
obj.createTree(&obj.tree,item);
}
break;
case 2 :

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout<<"\n\nInorder Traversal : ";


obj.inOrder(obj.tree);
getch();
break;
case 3 :
cout<<"\n\nPreorder Traversal : ";
obj.preOrder(obj.tree);
getch();
break;
case 4 :
cout<<"\n\nPostorder Traversal : ";
obj.postOrder(obj.tree);
getch();
break;
case 5 :
exit(1);
}//end of switch
}
}
Output:
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 1
--Creating Tree
How many nodes u want to enter : 4
Enter value : 12
Enter value : 34
Enter value : 45
Enter value : 67
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

4) Postorder Traversal
5) Exit
Enter your choice : 2
Inorder Traversal : 12 34 45 67
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 3
Preorder Traversal :12 45 34 67
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 4
Postorder Traversal : 34 67 45 12
Tree Traversal
1) Create Tree
2) Inorder Traversal
3) Preorder Traversal
4) Postorder Traversal
5) Exit
Enter your choice : 5
Result:
Thus the program for binary search tree traversal operations is executed
successfully.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Ex.No:14

MINIMUM SPANNING TREES

Given a connected, undirected graph, a spanning tree of that graph is a sub


graph that is a tree and connects all the verticestogether. A single graph can have
many different spanning trees. We can also assign a weight to each edge, which is
a number representing how unfavorable it is, and use this to assign a weight to a
spanning tree by computing the sum of the weights of the edges in that spanning
tree. A minimum spanning tree (MST) or minimum weight spanning tree is then a
spanning tree with weight less than or equal to the weight of every other spanning
tree.
Ex: (i) Write a c++ program for minimum spanning tree using Kruskal's
algorithm.
Aim:
To write a c++ program for minimum spanning tree using Kruskal's
algorithm.
Algorithm:
Step1: start the program.
Step2: sort the edges of G in increasing order by length
Step3: keep a subgraph S of G, initially empty
Step4: for each edge e in sorted order
Step5: if the endpoints of e are disconnected in S
Step6: add e to S
Step7: return S
Step8: Stop the program
Program:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,m,c,visit,visited[10],l,v,count,count1,vst,p;
main()
{
int dup1,dup2;
cout<<"enter no of vertices";
cin >> n;

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

cout <<"enter no of edges";


cin >>m;
cout <<"EDGE Cost";
for(k=1;k<=m;k++)
{
cin >>i >>j >>c;
cost[i][j]=c;
cost[j][i]=c;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]==0)
cost[i][j]=31999;
visit=1;
while(visit<n)
{
v=31999;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]!=31999 && cost[i][j]<v && cost[i][j]!=-1 )
{
int count =0;
for(p=1;p<=n;p++)
{
if(visited[p]==i || visited[p]==j)
count++;
}
if(count >= 2)
{
for(p=1;p<=n;p++)
if(cost[i][p]!=31999 && p!=j)
dup1=p;
for(p=1;p<=n;p++)
if(cost[j][p]!=31999 && p!=i)
dup2=p;
if(cost[dup1][dup2]==-1)
continue;
}
l=i; k=j;
v=cost[i][j];

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
cout <<"edge from " <<l <<"-->"<<k;
cost[l][k]=-1;
cost[k][l]=-1;
visit++;
int count=0;
count1=0;
for(i=1;i<=n;i++)
{
if(visited[i]==l)
count++;
if(visited[i]==k)
count1++;
}
if(count==0)
visited[++vst]=l;
if(count1==0)
visited[++vst]=k;
}
}
Output:
enter no of vertices4
enter no of edges4
EDGE Cost
121
232
343
133
edge from 1>2edge from 2>3 edge from 1>3
Result:
Thus the program for minimum spanning tree using Kruskal's algorithm is
executed successfully.
Ex: (ii) Write a c++ program for minimum spanning tree using Prims
algorithm.
Aim:
To write a c++ program for minimum spanning tree using Prim's algorithm.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Algorithm:
Step1: start the program.
Step2: let T be a single vertex x
Step3: while (T has fewer than n vertices)
Step4: find the smallest edge connecting T to G-T
Step5: add it to T
Step6: repeat step 4 and 5 for all n vertices
Step7: Stop the program
Program:
#include <iostream.h>
#include <conio.h>
#define ROW 7
#define COL 7
#define infi 5000 //infi for infinityclass prims
{
int graph[ROW][COL],nodes;
public:
prims();
void createGraph();
void primsAlgo();
};
prims :: prims(){
for(int i=0;i<ROW;i++)
for(int j=0;j<COL;j++)
graph[i][j]=0;
}
void prims :: createGraph(){
int i,j;
cout<<"Enter Total Nodes : ";
cin>>nodes;
cout<<"\n\nEnter Adjacency Matrix : \n";
for(i=0;i<nodes;i++)
for(j=0;j<nodes;j++)
cin>>graph[i][j];
//Assign infinity to all graph[i][j] where weight is 0.for(i=0;i<nodes;i++){

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

for(j=0;j<nodes;j++){
if(graph[i][j]==0)
graph[i][j]=infi;
}
}
}
void prims :: primsAlgo(){
int selected[ROW],i,j,ne; //ne for no. of edgesintfalse=0,true=1,min,x,y;
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<<"\n"<<x+1<<" --> "<<y+1;
ne=ne+1;
}
}
void main(){
prims MST;
clrscr();
cout<<"\nPrims Algorithm to find Minimum Spanning Tree\n";

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

MST.createGraph();
MST.primsAlgo();
getch();
}
Output:
Prims algorithm to find minimum spanning tree
Enter Total Nodes: 3
Enter Adjancy Matrix:
9
6
3
2
8
7
4
3
0
13
32
Result:
Thus the program for minimum spanning tree using Prim's algorithm is
executed successfully.

Ex.No:15

SHORTEST PATH ALGORITHMS

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

In graph theory, the shortest path problem is the problem of finding a path
between two vertices (or nodes) in a graph such that the sum of the weights of its
constituent edges is minimized.Dijkstra's algorithm solves the single-source
shortest path problem. BellmanFord algorithm solves the single-source problem if
edge weights may be negative.FloydWarshall algorithm solves all pairs shortest
paths.
Ex: (i) Write a c++ program to find the shortest path in the graph using
Dijkstras algorithm.
Aim:
To write a c++ program to find the shortest path in the graph using
Dijkstras algorithm.
Algorithm:
Step 1: Start the program.
Step 2: Assign to every node a tentative distance value: set it to zero for our initial
node and to infinity for all other nodes.
Step 3: Mark all nodes unvisited.
Step 4: Set the initial node as current.
Step 5: Create a set of the unvisited nodes called the unvisited set consisting of all
the nodes.
Step 6: For the current node, consider all of its unvisited neighbors and calculate
their tentative distances.
Step 7: Compare the newly calculated tentative distance to the current assigned
value and assign the smaller one.
Step 8: Mark the current node as visited and remove it from the unvisited set.
Step 9: If the destination node has been marked visited or if the smallest tentative
distance among the nodes in the unvisited set is infinity then stop.
Step 10: Select the unvisited node that is marked with the smallest tentative
distance, and set it as the new "current node" then go back to step 6.
Step 11: Stop the program.
Program:
#include<iostream>
#define INFINITY 999
using namespace std;
class Dijkstra{
private:
int adjMatrix[15][15];

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

int predecessor[15],distance[15];
bool mark[15]; //keep track of visited node
int source;
int numOfVertices;
public:
void read();
void initialize();
while((source<0) && (source>numOfVertices-1)) {
cout<<"Source vertex should be between 0 and"<<numOfVertices-1<<endl;
cout<<"Enter the source vertex again\n";
cin>>source;
}
}
void Dijkstra::initialize(){
for(int i=0;i<numOfVertices;i++) {
mark[i] = false;
predecessor[i] = -1;
distance[i] = INFINITY;
}
distance[source]= 0;
}
int Dijkstra::getClosestUnmarkedNode(){
int minDistance = INFINITY;
int closestUnmarkedNode;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && ( minDistance >= distance[i])) {
minDistance = distance[i];
closestUnmarkedNode = i;
}
}
return closestUnmarkedNode;
}
void Dijkstra::calculateDistance(){
initialize();
int minDistance = INFINITY;
int closestUnmarkedNode;
int count = 0;
while(count < numOfVertices) {

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

closestUnmarkedNode = getClosestUnmarkedNode();
mark[closestUnmarkedNode] = true;
for(int i=0;i<numOfVertices;i++) {
if((!mark[i]) && (adjMatrix[closestUnmarkedNode][i]>0) ) {
if(distance[i] >
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i]) {
distance[i] =
distance[closestUnmarkedNode]+adjMatrix[closestUnmarkedNode][i];
predecessor[i] = closestUnmarkedNode;
}
}
}
count++;
}
}
void Dijkstra::printPath(int node){
if(node == source)
cout<<(char)(node + 97)<<"..";
else if(predecessor[node] == -1)
cout<<"No path from <<source<<to "<<(char)(node + 97)<<endl;
else {
printPath(predecessor[node]);
cout<<(char) (node + 97)<<"..";
}
}
void Dijkstra::output(){
for(int i=0;i<numOfVertices;i++) {
if(i == source)
cout<<(char)(source + 97)<<".."<<source;
else
printPath(i);
cout<<"->"<<distance[i]<<endl;
}
}
int main(){
Dijkstra G;
G.read();
G.calculateDistance();

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

G.output();
return 0;
}
Output:
Enter the number of vertices of the graph(should be >0) 6
Enter the adjacency matrix for the graph
To enter infinity enter 999
Enter the (+ve) weights for the row 0
0 4 2 999 999 999
Enter the (+ve) weights for the row 1
4 0 1 5 999 999
Enter the (+ve) weights for the row 2
2 1 0 8 10 999
Enter the (+ve) weights for the row 3
999 5 8 0 2 6
Enter the (+ve) weights for the row 4
999 999 10 2 0 3
Enter the (+ve) weights for the row 5
999 999 999 6 3 0
Enter the source vertex 0
a..0->0
a..c..b..->3
a..c..->2
a..c..b..d..->8
a..c..b..d..e..->10
a..c..b..d..e..f..->13
Result:
Thus the program to find shortest path using Dijkstra's algorithm is executed
successfully.

Ex: (ii) Write a c++ program to find the shortest path in the graph using
Floyd Warshalls algorithm.
Aim:
To write a c++ program to find the shortest path in the graph using Floyd
Warshalls algorithm.

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Algorithm:
Step 1: Start the program.
Step 2: Get the value of distance matrix in a |V| |V| array.
Step3:for each vertex v, do dist[v][v] 0
Step4: for each edge (u,v), do dist[u][v] w(u,v) // the weight of the edge (u,v)
Step 5: if dist[i][j] > dist[i][k] + dist[k][j]
Step 6: then assign dist[i][j] dist[i][k] + dist[k][j]
Step 7: Repeat step 5 and 6 for all pair of vertices.
Step 8: Display the shortest distance between all pair of vertices.
Step 9: Stop the program.
Program:
#include <iostream>
#include <conio.h>
using namespace std;
void floyds(int b[][7])
{
int i, j, k;
for (k = 0; k < 7; k++)
{
for (i = 0; i < 7; i++)
{
for (j = 0; j < 7; j++)
{
if ((b[i][k] * b[k][j] != 0) && (i != j))
{
if ((b[i][k] + b[k][j] < b[i][j]) || (b[i][j] == 0))
{
b[i][j] = b[i][k] + b[k][j];
}
}
}
}
}
for (i = 0; i < 7; i++)
{
cout<<"\nMinimum Cost With Respect to Node:"<<i<<endl;
for (j = 0; j < 7; j++)
{
cout<<b[i][j]<<"\t";

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

}
}
}
int main()
{
int b[7][7];
cout<<"ENTER VALUES OF ADJACENCY MATRIX\n\n";
for (int i = 0; i < 7; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{
cin>>b[i][j];
}
}
floyds(b);
getch();
}
Output
ENTER VALUES OF ADJACENCY MATRIX
enter values for 1 row
0
3
6
0
0
0
0
enter values for 2 row
3
0
2
4
0
0
0
enter values for 3 row
6
2

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

0
1
4
2
0
enter values for 4 row
0
4
1
0
2
0
4
enter values for 5 row
0
0
4
2
0
2
1
enter values for 6 row
0
0
2
0
2
0
1
enter values for 7 row
0
0
0
4
1
1
0
Minimum Cost With Respect to Node:0
0
3
5
6
8
7
8

cseitquestions.blospot.in | cseitquestions.blospot.in | cseitquestions.blospot.in

Minimum Cost With Respect to Node:1


3
0
2
3
5
4
5
Minimum Cost With Respect to Node:2
5
2
0
1
3
2
3
Minimum Cost With Respect to Node:3
6
3
1
0
2
3
3
Minimum Cost With Respect to Node:4
8
5
3
2
0
2
1
Minimum Cost With Respect to Node:5
7
4
2
3
2
0
1
Minimum Cost With Respect to Node:6
8
5
3
3
1
1
0
Result:
Thus the program to find the shortest path in the graph using Floyd
Warshalls algorithm is executed successfully.

Potrebbero piacerti anche