Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
in
PREPARED BY
Dr.G.RAMESH Professor/IT
SYLLABUS
CS6311
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.
LIST OF EXPERIMENTS
EX.NO
1
FRIEND FUNCTION
INHERITANCE
a. POLYMORPHISM
b. FUNCTION OVERLOADING
VIRTUAL FUNCTIONS
OPERATOR OVERLOADING
a. CLASS TEMPLATES
b. FUNCTION TEMPLATES
10
11
12
13
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
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
Ex.No:1(a)
CONSTRUCTORS
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
{
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);
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
~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
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
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
{
//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:;
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();
}
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().
{
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
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 :;
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()
{
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
Salary:10000
Result:
Thus the c++ program for employee database using multiple inheritancesis
executed successfully.
Ex.No:4(a)
POLYMORPHISM
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);
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>
#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
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)
{
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.
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:
};
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.
Ex.No:6
OPERATOR OVERLOADING
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>
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";
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>
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;
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.
Ex.No:7(a)
FUNCTION TEMPLATES
#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
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:
Ex.No:8
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);
}
}
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.
Ex.No:9
Description
Containers
Algorithms
Iterators
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()
{
// 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:
Thus the c++ program for standard template library (vector container)is
executed successfully.
Ex.No:10
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.
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;
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);
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:
}
}
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);
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
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.
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 *);
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;
}
//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);
}
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();
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
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
Ex.No:13
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;
};
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);
}
}
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
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.
Ex.No:14
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;
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.
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;
}
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.
Ex.No:15
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];
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 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.
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];
}
}
}
}
}
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
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.
PREPARED BY
Dr.G.RAMESH Professor/IT
SYLLABUS
CS6311
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:
LIST OF EXPERIMENTS
EX.NO
1
FRIEND FUNCTION
INHERITANCE
a. POLYMORPHISM
b. FUNCTION OVERLOADING
VIRTUAL FUNCTIONS
OPERATOR OVERLOADING
a. CLASS TEMPLATES
b. FUNCTION TEMPLATES
10
11
12
13
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
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
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
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++)
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.
Ex.No:1(b)
DESTRUCTORS
constructor 2
destructor 1
destructor 0
Result:
Thus the c++ program for destructor function is executed successfully.
Ex.No:1(c)
COPY CONSTRUCTOR
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:
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.
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:
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:
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];
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;
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.
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;
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.
Ex.No:4(a)
POLYMORPHISM
{
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();
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>
#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
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.
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.
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" ;
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.
Ex.No:6
OPERATOR OVERLOADING
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()
{
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();
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.
Ex.No:7(a)
FUNCTION TEMPLATES
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.
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;
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.
Ex.No:8
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
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
Algorithms
Iterators
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()
{
Thus the c++ program for standard template library (vector container)is
executed successfully.
Ex.No:10
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.
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())!='#')
{
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
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:
{
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;
}
}
}
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
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.
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);
};
//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){
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
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";
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
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.
Ex.No:13
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;
};
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;
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 :
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.
Ex.No:14
}
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.
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++){
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";
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
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];
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) {
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();
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.
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";
}
}
}
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
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