Professional Documents
Culture Documents
Cs6311 Pds Lab Manualnew
Cs6311 Pds Lab Manualnew
Cs6311 Pds Lab Manualnew
com
WWW.VIDYARTHIPLUS.COM
a) Single Inheritance
b) Multiple Inheritance
d) Hybrid Inheritance
a) Polymorphism
b) Function Overloading
6. Overloading unary and binary operator using Member function and Non-member function
a) Function Template
b) Class Template
8. Exception Handling
a) Division by zero
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
9. STL Concepts
a) Container
b) Allocator
c) Iterator
d) Function Adaptors
i) Reading from and writing the personal details into the file using getline function
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
a) Stack Implementation
b) Queue Implementation
a) Prim's Algorithm
b) Kruskal Algorithm
a) Dijkstra's Algorithm
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
public:
//default constructor
StudentDetails ()
{
}
//parameterized constructor
StudentDetails (int student_mark, char student_grade)
{
mStudentmarks = student_mark;
mStudentgrade = student_grade;
}
//copy constructor
StudentDetails (StudentDetails & oStudent)
{
mStudentmarks = oStudent.mStudentmarks;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
mStudentgrade = oStudent.mStudentgrade;
}
//dynamic constructor
StudentDetails (char* pStudent)
{
mName = strlen(pStudent);
pStudentname = new char[mName+1];
strcpy(pStudentname,pStudent);
}
//member function
void StudentName()
{
cout << "Studentname \t " << pStudentname<<endl;
}
//member function
void StudentMark()
{
cout << "StudentMarks =" << mStudentmarks << endl;
cout << "StudentGrade = " << mStudentgrade << endl;
}
~ StudentDetails ()
{
}
};
int main()
{
// objects created for the class
StudentDetails oStudent1(730,
'A'),oStudent2(621,'B'),oHighestMark(oStudent1);
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
#include<iostream>
#include<string>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class friends
{
//access specifies
private:
// initialization of member variables
int mVar1,mVar2;
//access specifier
public:
// member function
void test()
{
// assigning value to member variables
cout<<"Enter the first value :";
cin>>mVar1;
cout<<"Enter the second value :";
cin>>mVar2;
}
// Function one
int addition(friends input)
{
// addition operation performed
return int(input.mVar1 + input.mVar2);
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
// Function two
int subtraction(friends input)
{
// subtraction operation performed
return int(input.mVar2- input.mVar1);
}
// main function
int main( )
{
// object created
friends ofriend;
//accessing member function using the object
ofriend.test();
//print the output of addition
cout << "The addition value is:"<<addition(ofriend) << endl;
// print the output of subtraction
cout << "The subtraction value is:"<<subtraction(ofriend) << endl;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class Square;
class Rectangle
{
int width, height;
public:
int area ()
{
return ( width * height );
}
class Square
{
private:
int side;
public:
Square ( int a ) : side ( a ) {}
};
int main ()
{
Rectangle rect;
Square sqr ( 4 );
rect.convert ( sqr );
cout << rect.area();
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
a) Single Inheritance
#include<iostream>
using namespace std;
//Base class Employee
class Employee
{
public:
int mEmployee_number;
char mEmployee_name[20], mEmployee_destination[20];
void Getdetails1()
{
cout << "Enter the Employee number:";
cin >> mEmployee_number;
cout << "Enter the Employee name:";
cin >> mEmployee_name;
cout << "Enter the designation:";
cin >> mEmployee_destination;
}
};
//Derived Class salary from Employee
class salary: public Employee
{
float B_pay, HR_Allowance, D_Allowance, P_Fund, Netpay;
public:
void Getdetails2()
{
cout << "Enter the basic pay:";
cin >> B_pay;
cout << "Enter the Humen Resource Allowance:";
cin >> HR_Allowance;
cout << "Enter the Dearness Allowance :";
cin >> D_Allowance;
cout << "Enter the Profitablity Fund:";
cin >> P_Fund;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void calculate()
{
Netpay = B_pay + HR_Allowance + D_Allowance - P_Fund;
}
void display()
{
cout << mEmployee_number << "\t" << mEmployee_name << "\t" <<
mEmployee_destination << "\t" << B_pay << "\t" << HR_Allowance << "\t" <<
D_Allowance << "\t" << P_Fund << "\t" << Netpay << "\n";
}
};
int main()
{
int Var_i, Var_n;
char Var_ch;
salary Var_s[10];
cout << "Enter the number of Employee:";
cin >> Var_n;
for ( i = 0;i < n;i++ )
{
Var_s[Var_i].Getdetails1();
Var_s[Var_i].Getdetails2();
Var_s[Var_i].calculate();
}
cout << "\n number name destination B_pay HR_Allowance
D_Allowance P_Fund Netpay ";
for ( Var_i = 0;Var_i < Var_n;Var_i++ )
{
Var_s[Var_i].display();
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
b) Multiple Inheritance
#include <iostream>
using namespace std;
//base class1
class Area
{
public:
float area_calculate ( float l, float b )
{
return l*b;
}
};
//base class2
class Perimeter
{
public:
float peri_calculate ( float l, float b )
{
return 2* ( l + b );
}
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
float area_calc()
{
/* Calls area_calc() of class Area and returns it. */
float peri_calc()
{
/* Calls peri_calc() function of class Perimeter and returns it. */
int main()
{
//object created
Rectangle oRectangle;
oRectangle.get_data();
cout << "Area = " << oRectangle.area_calculate();
cout << "\n Perimeter = " << oRectangle.peri_calculate();
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
bottom b1;
b1.cube();
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Output
d) Hybrid Inheritance
#include<iostream>
#include<string.h>
class StudentResult
{
int mStud_Rollno;
public:
//member function of base class
void GetRollnumber()
{
cout << "Enter Roll No:";
cin >> mStud_Rollno;
}
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
cout << "\n\n\tRoll No:" << mStud_Rollno << "\n";
}
};
public:
int mSubject1,mSubject2;
// member function of derived class
void GetSubjectmarks()
{
cout << "Enter Marks\n";
cout << "subject1:";
cin >> mSubject1;
cout << "subject2:";
cin >> mSubject2;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
public:
// member variable
int mScore;
//member function
void GetSportsscore()
{
cout << "Enter Sports Score:";
cin >> mScore;
}
//member function
void PutSportsscore()
{
cout << "\n\tSports Score is:" << mScore;
}
};
public:
//derived class function
void mDisplay()
{
mTotal = mSubject1 + mSubject2 + mScore;
PutRollnumber();
PutSubjectmarks();
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
PutSportsscore();
cout << "\n\t Total Score:" << mTotal;
}
};
int main()
{
// object created for only one class ( finally which was derived)
Result oStudentResult;
oStudentResult.GetRollnumber();
oStudentResult.GetSubjectmarks();
oStudentResult.GetSportsscore();
oStudentResult.mDisplay();
}
Output:
a) Polymorphism
#include<iostream>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
//class
class Shape
{
protected:
//member variable
double mLength;
double mBreath;
public:
//Member function
void Getdata(double mLength1,double mBreath1)
{
mLength=mLength1;
mBreath=mBreath1;
}
public:
void display()
{
Var_T=0.5*mLength*mBreath;
cout<<"\nArea of the triangle :";
cout<<Var_T;
}
};
//Derived class 2
class rectangle:public Shape
{
double Var_R;
public:
void display()
{
Var_R=mLength*mBreath;
cout<<"\nArea of rectangle :";
cout<<Var_R;
}
};
//derived class 3
class circle:public Shape
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
double Var_C;
public:
void display()
{
Var_C=3.14*mLength*mLength;
cout<<"\nArea of the circle :";
cout<<Var_C;
}
};
int main()
{
double Breath,Height;
triangle oTriangle;
rectangle oRectangle;
circle oCircle;
cout<<"\n Enter two values for area calculation:";
cin>>Breath>>Height;
oTriangle.Getdata(Breath,Height);
oRectangle.Getdata(Breath,Height);
oCircle.Getdata(Breath,0);
oTriangle.display();
oRectangle.display();
oCircle.display();
}
Output
b) Function Overloading
#include <iostream>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
//class
class PrintData
{
public:
//member function to get integer value
void Print(int mIntValue)
{
cout << "Printing int: " << mIntValue << endl;
}
int main(void)
{
PrintData oPrintData;
// Call print to print integer
oPrintData.Print(5);
// Call print to print float
oPrintData.Print(500.263);
// Call print to print character
oPrintData.Print("Hello C++");
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int getresult()
{
return mResult;
}
};
// add class inherits from base class
class rectangle: public Shape
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
public:
void area()
{
mResult = mWidth*mHeight;
}
};
public:
void area()
{
mResult= ( mWidth*mHeight)/2;
}
};
int main()
{
int Length,Breath;
//pointer variable declaration of type base class
Shape* oShape;
//create object1 for addition process
rectangle oRectangle;
//create object2 for subtraction process
triangle oTriangle;
cout << "\nEnter the width and height: ";
oShape->area();
cout << "\nArea of triangle = " << oShape->getresult() << endl;
}
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class ComplexOperations
// Access specifies
private:
float mRealnumber;
float mImaginarynumber;
public:
ComplexOperations()
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
mRealnumber = real;
mImaginarynumber = imaginary;
mRealnumber = real;
mImaginarynumber = imaginary;
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return input;
if ( oComplex.mImaginarynumber < 0 )
else
return output;
ComplexOperations oAddition;
return oAddition;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
ComplexOperations oSubtraction;
return oSubtraction;
ComplexOperations oMulti;
return oMulti;
ComplexOperations oDivision;
float result_of_complexoperations;
result_of_complexoperations = oComplex.mRealnumber *
oComplex.mRealnumber + oComplex.mImaginarynumber *
oComplex.mImaginarynumber;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return oDivision;
int main()
return 0;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Output
a) Function Template
#include <iostream>
#include <string>
using namespace std;
// Function template declaration
template <typename T>
inline T const& Max (T const& number_one, T const& number_two)
{
// Returns greatest number
return number_one < number_two ? number_two : number_one;
}
int main ()
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
// Integer variables declaration
int int_number_one, int_number_two;
// Double variables declaration
double double_number_one, double_number_two;
// String variables declaration
string string_word_one, string_word_two;
cout << "Enter integer values";
cin >> int_number_one >> int_number_two;
// Function call to template
cout << "Integer Result:" << Max(int_number_one, int_number_two);
cout << "Enter double values";
cin >> double_number_one >> double_number_two;
cout << "Double Result:" << Max(double_number_one, double_number_two);
cout << "Enter string values";
cin >> string_word_one >> string_word_two;
cout << "String Result:" << Max(string_word_one, string_word_two);
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
b) Class Template
#include <iostream>
using namespace std;
// Class template declaration
template <class T>
class GreatestNumber
{
// Member variable declaration
T mNumberone, mNumbertwo;
public:
GreatestNumber (T first, T second)
{
mNumberone=first; mNumbertwo=second;
}
// Function call
T GetMax ();
};
// Class template declaration
template <class T>
T GreatestNumber<T>::GetMax ()
{
T mReturnvalue;
mReturnvalue = mNumberone > mNumbertwo ? mNumberone : mNumbertwo;
return mReturnvalue;
}
/*
Main function which takes the number_one and number_two
as input and print the greatest of two numbers using
function template.
*/
int main ()
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
int number_one, number_two;
cout << "enter two number";
cin >> number_one >> number_two;
GreatestNumber <int> myobject (number_one, number_two);
cout << "The greatest number is "<< myobject.GetMax();
return 0;
}
Output:
8. Exception Handling
a) Division by zero
#include<iostream>
using namespace std;
int main()
{
// Integer variables declaration
int number_one,number_two,number_three;
// Floating variables declaration
float number_four;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ((number_one-number_two)!=0)
{
// Get the division values
number_four=number_three/(number_one-number_two);
cout<<"Result is:"<< number_four;
}
else
{
// throws the value
throw(number_one-number_two);
}
}
// catch the integer number
catch (int int_Numberone)
{
cout<<"Answer is infinite because a-b is:"<<int_Numberone;
}
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
//Function definition
double Division(int Number_one, int Number_two)
{
// chexk the number equals to zero
if ( Number_two == 0 )
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
// Throws the statement
throw "Division by zero condition!";
}
return (Number_one/Number_two);
}
int main ()
{
//Integer variables declaration
int int_Numberone,int_Numbertwo;
// Dobule variable initialized with zero
double double_Numberone = 0;
cout << "Enter the integer values";
cin >> int_Numberone >> int_Numbertwo;
//try function
try
{
// Function Call to division()
double_Numberone = Division(int_Numberone, int_Numbertwo);
cout << double_Numberone << endl;
}
// catch function
catch (const char* divisionvalue )
{
// Print the error statement of division
cerr << divisionvalue << endl;
}
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
int StudentAge;
try
{
cout << "Student Age: ";
cin >> StudentAge;
/*Check whether the student age is greater than zero */
if ( StudentAge < 0 )
throw "Positive Number Required";
// Print the student age
cout << "\n Student Age: " << StudentAge << "\n\n";
}
// Catch the "Positive Number Required" exception.
catch ( const char* Message )
{
cout << "Error: " << Message;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
/*
* Pre conditions: all the four marks must be between
* 0 -100 otherwise the function throws a OutOfRangeException
* Post condition: returns the average of the four marks
* Invariants: avg >= 0 && avg <=100
*/
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main ()
{
// Integer variables declaration
int mark1, mark2, mark3, mark4;
cout << "****Enter four marks for four subject ranges 0 - 100 to avoid
exception****\n";
cout << "First mark";
cin >> mark1;
cout << "\n Second mark";
cin >> mark2;
cout << "\n Third mark";
cin >> mark3 ;
cout << "\n Fourth mark";
cin >> mark4;
try
{
float average = calculateAverage ( mark1, mark2, mark3, mark4 );
cout << "Average of four marks\n" << average;
}
catch ( OutOfRangeException )
{
cout << "Exception occurred (**) OutOfRangeException**)\n";
cerr << "Marks out of range" << endl;
}
// system("pause");
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
// Variables declaration
char Number1[40], Number2[40];
double Operand1, Operand2, Result;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
char Operator;
case '-':
Result = Operand1 - Operand2;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
break;
case '*':
Result = Operand1 * Operand2;
break;
case '/':
Result = Operand1 / Operand2;
break;
}
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
9. STL Concepts
a) Container
STL Container-vector operators
#include <vector>
#include <iostream>
using namespace std;
int main ()
{
unsigned int i;
// vector container for integer elements
vector<int> vec1, vec2, vec3;
int size_one, size_two, size_three;
cout << "Enter the size for three vectors";
cin >> size_one >> size_two >> size_three;
// print vector data
cout << "vec1 vector data: ";
// append elements with given values
for ( i = 1; i <= size_one; ++i )
vec1.push_back ( i );
// print all elements separated by a space
for ( i = 0; i < vec1.size(); ++i )
cout << vec1[i] << ' ';
cout << endl;
cout << "vec2 vector data: ";
// append elements with given values
for ( i = 1; i <= size_two; ++i )
vec2.push_back ( i );
// print all elements separated by a space
for ( i = 0; i < vec2.size(); ++i )
cout << vec2[i] << ' ';
cout << endl;
cout << "vec3 vector data: ";
// append elements with given values
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
cout << "vec1 vector less or equal than vec2 vector." << endl;
else
cout << "vec1 vector is not less or equal than vec2 vector." << endl;
return 0;
}
Output
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
cout << "The number of elements in vector_two = " << vector_two.size() <<
endl;
cout << endl;
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
string str1[100];
cout << "Enter the element to append into the vector";
cin >> str;
// append some elements
sentence.push_back ( str );
cout << "Enter strings to add in the vector";
for ( int i = 0;i < 5;i++ )
cin >> str1[i];
for ( int j = 0;j < 5;j++ )
{
sentence.insert ( sentence.end(), str1[j] );
}
// print elements separated with spaces
copy ( sentence.begin(), sentence.end(),
ostream_iterator<string> ( cout, " " ) );
cout << endl;
// print ``technical data''
cout << " max_size(): " << sentence.max_size() << endl;
cout << " size(): " << sentence.size() << endl;
cout << " capacity(): " << sentence.capacity() << endl;
int position;
string new_string;
cout << "Enter the position to insert the new string";
cin >> position;
cout << "Enter the new string";
cin >> new_string;
// insert element "always" before element "?"
sentence.insert ( find ( sentence.begin(), sentence.end(),
sentence[position-1] ),
new_string );
// assign "!" to the last element
sentence.back() = "!";
// print elements separated with spaces
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
b) Allocator
#include <iostream>
#include <algorithm>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
#include <string>
class Account
{
private :
std::string owner_name;
int credit;
int potential_credit_transfer;
public :
Account() {}
Account ( std::string name, int initial_credit, int
initial_credit_transfer ) :
owner_name ( name ),
credit ( initial_credit ),
potential_credit_transfer ( initial_credit_transfer )
{}
struct CompareAccountCredit
{
bool operator() ( Account const& account1, Account const& account2 )
const
{
return account1 < account2;
}
};
struct CompareAccountPotentialCredit
{
bool operator() ( Account const& account1, Account const& account2 )
const
{
return account1.potential_credit() < account2.potential_credit();
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
};
int main()
{
Account account1 ( "Dennis Ritchie", 1000, 250 ), account2 ( "Steeve Jobs",
500, 10000 ),
result_comparison;
return 0;
}
Output
c) Iterator
Iterator - a list container
#include <iostream>
#include <list>
using namespace std;
int main()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Output:
int main()
{
// set container of int data type
set<int> tst;
// insert elements
tst.insert ( 12 );
tst.insert ( 21 );
tst.insert ( 32 );
tst.insert ( 31 );
tst.insert ( 9 );
tst.insert ( 14 );
tst.insert ( 21 );
tst.insert ( 31 );
tst.insert ( 7 );
// iterate over all elements and print, separated by space
set<int>::const_iterator pos;
// pre-increment and pre-decrement are faster than post-increment and post-
decrement...
for ( pos = tst.begin(); pos != tst.end(); ++pos )
cout << *pos << ' ';
cout << endl;
return 0;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Output
int main()
{
// multiset container of int data type
multiset<int> tst;
// insert elements
tst.insert ( 12 );
tst.insert ( 21 );
tst.insert ( 32 );
tst.insert ( 31 );
tst.insert ( 9 );
tst.insert ( 14 );
tst.insert ( 21 );
tst.insert ( 31 );
tst.insert ( 7 );
// iterate over all elements and print, separated by space
multiset<int>::const_iterator pos;
// pre-increment and pre-decrement are faster than post-increment and post-
decrement...
for ( pos = tst.begin(); pos != tst.end(); ++pos )
cout << *pos << ' ';
cout << endl;
return 0;
}
Output
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
#include <string>
using namespace std;
int main()
{
// type of the collection
map<int, string> mp;
int main()
{
// type of the collection
multimap<int, string> mmp;
// set container for int/string values insert some elements in arbitrary
order
// notice a value of key 1
mmp.insert ( make_pair ( 5, "learn" ) );
mmp.insert ( make_pair ( 2, "map" ) );
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
d) Function Adaptors
#include <iostream>
#include <algorithm>
template<class T>
struct PrintData
{
PrintData ( std::ostream &out ) : os_ ( out ), count_ ( 0 ) {}
void operator() ( T x )
{
os_ << x << ' ';
++count_;
};
std::ostream &os_;
int count_;
};
int main ()
{
int array[] = {1, 4, 2, 8, 5, 7};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
std::cout << std::endl << std::endl << f.count_ << " objects printed." <<
std::endl;
return 0;
}
Output
int main()
{
// Create object to display output
ofstream oFileoutput;
// Open the text file in write mode
oFileoutput.open ( "out.txt" );
//String declaration
char char_string[300] = "Time is a great teacher, but unfortunately it
kills all its students. Berlioz";
//Display the string
oFileoutput << char_string;
//Close the text file in write mode
oFileoutput.close();
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
// Create object to get input values
ifstream oFileinput;
// Open the text file in read mode
oFileinput.open ( "out.txt" );
// Character declaration
char char_text;
/* Read the character until the file reach end of file*/
while ( !oFileinput.eof() )
{
oFileinput.get ( char_text );
//Display the text
cout << char_text;
}
//Close the text file opened in read mode
oFileinput.close();
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
// Create object to get input values
ifstream oFileinput;
// Open the text file in read mode
oFileinput.open ( "out.txt" );
// Character declaration
char char_text;
//Integer variable declaration
int int_count = 0;
/* Read the character until the file reach end of file*/
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
while ( !oFileinput.eof() )
{
// Read characters from the text file
oFileinput.get ( char_text );
// Increment the count values
int_count++;
}
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
#include<fstream>
#include<conio.h>
int main()
{
// Create object to read input values
ifstream oFileinput;
// Open the text file in read mode
oFileinput.open ( "out.txt" );
// Character declaration
char char_word[30];
//Integer variable declaration
int int_count = 0;
/* Read the word until the file reach end of file*/
while ( !oFileinput.eof() )
{
//Read the word from the text file
oFileinput >> char_word;
// Increment the count values
int_count++;
}
return 0;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
// Read the word from the text file
oFileinput >> char_word;
// Increment the count values
int_count++;
}
// Display number of words in text file
cout << "Number of words in file is " << int_count;
// Close the text file opened in read mode
oFileinput.close();
return 0;
}
Output
#include<iostream>
#include<fstream>
#include<conio.h>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
while ( !oFileinput.eof() )
{
// Read characters from the "out.txt"
oFileinput.get ( char_text );
// Write characters to "sample.txt"
oFileoutput << char_text;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
struct StudentDetails
{
int RollNo; char
Name[30]; char
Address[40];
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int main()
{
if ( !BE_StudFile_Output.is_open() )
{
do
{
ReadStudentDetails ( BE_Student_Output );
BE_StudFile_Output.write ( ( char* ) &BE_Student_Output, sizeof (
struct StudentDetails ) );
if ( BE_StudFile_Output.fail() )
{
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
else
{
BE_StudFile_Output.close();
return 0;
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
struct StudentDetails
{
int RollNo; char
Name[30]; char
Address[40];
};
// function declaration
void WriteStudentDetails ( StudentDetails TempStud )
{
cout << "\n The Roll No:";
cout << TempStud.RollNo;
cout << "\n The Name:";
cout << TempStud.Name;
cout << "\n The Address:";
cout << TempStud.Address;
cout << "\n";
// Main function
int main()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
while ( !BE_StudFile_Input.eof() )
if ( BE_StudFile_Input.fail() )
{
break;
}
WriteStudentDetails ( BE_Student_Input );
}
BE_StudFile_Input.close();
return 0;
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
i) Reading from and writing the personal details into the file using getline
function
#include <fstream>
#include <iostream>
int main ()
{
char Personal_data[100];
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
ifstream oFileinput;
oFileinput.open ( "personalfile.dat" );
// again read the data from the file and display it.
oFileinput >> Personal_data;
cout << Personal_data << endl;
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
file_ASCII_result=txt_file_data-32;
oFileoutput<<file_ASCII_result;
}
oFileoutput.close();
//read the contents of file
ifstream oFileintput(char_filename);
cout<<"\n\n\t\tThe File contains\n\n";
while (oFileintput.eof()==0)
{
oFileintput.get(txt_file_data);
cout<<txt_file_data;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class StackImplementation
{
int mMaximumsize;
int mTopofstack;
int *pTemp;
public :
StackImplementation ( int );
void Push ( int );
int Pop();
int IsEmpty();
int IsFull();
void Display();
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
~StackImplementation();
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int StackImplementation::IsEmpty()
{
if ( mTopofstack == -1 )
return 1;
else
return 0;
}
void StackImplementation::Display()
{
if ( IsEmpty() )
cout << "Empty list" << endl;
else
{
cout << "The element in stack are:\n";
StackImplementation::~StackImplementation()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
delete [] pTemp;
}
void Menu()
{
cout << "Press <1 to 4> keys to perform the following stack operation \n ";
cout << "1.Inserting element into the stack " << endl;
cout << "2.Deleting the stack element" << endl;
cout << "3.Display" << endl;
cout << "4.Exit" << endl;
}
main()
{
int get_option;
int get_value, return_value;
StackImplementation oStack ( 10 );
cout << "Implementation of Stack and its operation" << endl;
Menu();
cout << "Enter your option: \n";
cin >> get_option;
case 1:
cout << "Enter element" << endl;
cin >> get_value;
oStack.Push ( get_value );
break;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 2:
return_value = oStack.Pop();
if ( return_value == -1 )
cout << "Element cannot be deleted as stack is empty" << endl;
else
cout << "Deleted element is " << return_value << endl;
break;
case 3:
oStack.Display();
break;
}
Menu();
return 0;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
b) Queue Implementation
#include<iostream>
#include<stdlib.h>
using namespace std;
class QueueImplementation
{
int mQueueArray[5];
int mRear, mFront;
public:
QueueImplementation()
{
mRear = -1;
mFront = -1;
}
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
mQueueArray[++mRear] = x;
}
void Dequeue()
{
if ( mFront == mRear )
{
cout << "Queue is underflow";
return;
}
void Display()
{
if ( mRear == mFront )
{
cout << "Queue is empty";
return;
}
main()
{
int get_choice, get_no_of_elements, get_element;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
QueueImplementation oQueue;
while ( 1 )
{
cout << "\nMenu";
cout << "\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\nEnter your choice";
cin >> get_choice;
switch ( get_choice )
{
case 1:
break;
case 2:
oQueue.Dequeue();
break;
case 3:
oQueue.Display();
break;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 4:
exit ( 0 );
break;
default:
cout << "Invalid";
break;
}
}
return ( 0 );
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class StackOperation
{
public:
char mStack[50];
int mTopOfStack;
StackOperation()
{
mTopOfStack = -1;
}
char Pop()
{
if ( IsStackEmpty() )
// Return value '#' indicates stack is empty
return ( '#' );
else
return ( mStack[mTopOfStack--] );
}
int IsStackEmpty()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ( mTopOfStack == -1 )
return ( 1 );
else
return ( 0 );
}
int IsStackFull()
{
if ( mTopOfStack == 49 )
return ( 1 );
else
return ( 0 );
}
};
class InfixToPostfix
{
char infix[50];
char postfix[50];
public:
void ReadInfixExpr()
{
cout << "\nEnter an infix expression:";
cin >> infix;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void ConvertToPostfix()
{
StackOperation oStackOperation;
int l, precedence, p;
char Entry1, Entry2;
p = 0;
if ( !WhiteSpace ( Entry1 ) )
{
switch ( Entry1 )
{
case '(':
oStackOperation.Push ( Entry1 );
break;
case ')':
break;
case '+':
case '-':
case '*':
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case '/':
if ( !oStackOperation.IsStackEmpty() )
{
precedence = PrecedenceSymbol ( Entry1 );
Entry2 = oStackOperation.Pop();
if ( !oStackOperation.IsStackEmpty() )
Entry2 = oStackOperation.Pop();
else
break;
}
oStackOperation.Push ( Entry1 );
break;
default:
postfix[p++] = Entry1;
break;
}
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
while ( !oStackOperation.IsStackEmpty() )
postfix[p++] = oStackOperation.Pop();
postfix[p] = '\0';
cout << "\nThe postfix expression is: " << postfix << endl;
}
case '/':
return ( 4 );
// Precedence of * is 3
case '*':
return ( 3 );
// Precedence of + is 2
case '+':
return ( 2 );
// Precedence of - is 1
case '-':
return ( 1 );
// Precedence of ( is 0
case '(':
return ( 0 );
default:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return ( -1 );
}
}
};
main()
{
char choice = 'y';
InfixToPostfix oInfixToPostfix;
return 0;
}
Output
d)
Evaluatio
n of
Postfix
Expressio
n
#include <iostream>
#include <stdlib.h>
#include <math.h>
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
} ;
PostfixExpressionEvaluation :: PostfixExpressionEvaluation( )
{
mTopofstack = -1 ;
{
if ( mTopofstack ==MAX - 1 )
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
}
int data = mStack[mTopofstack];
mTopofstack-- ;
return data ;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Push ( mReturnvalue ) ;
}
else
{
value1 = Pop( ) ;
value2 = Pop( ) ;
switch ( *ptemp )
{
case '+' :
result = value2 + value1 ;
break ;
case '-' :
result = value2 - value1 ;
break ;
case '/' :
result = value2 / value1 ;
break ;
case '*' :
result = value2 * value1 ;
break;
case '%' :
result = value2 % value1 ;
break ;
case '$' :
result = pow ( value2 , value1 ) ;
break ;
default :
cout << "Unknown operator" ;
exit ( 1 ) ;
}
Push ( result ) ;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
ptemp++ ;
}
}
void PostfixExpressionEvaluation :: Show( )
{
mReturnvalue = Pop ( ) ;
cout << "Result is: " << mReturnvalue ;
}
main( )
{
char expr[MAX] ;
cout << "\nEnterpostfix expression to be evaluated : " ;
cin.getline ( expr, MAX ) ;
PostfixExpressionEvaluation oPostfix ;
oPostfix.SetExpression ( expr ) ;
oPostfix.Evaluate( ) ;
oPostfix.Show( ) ;
return 0 ;
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class CircularQueue
{
int mQueue[MAX], mFront, mRear;
public :
CircularQueue()
{
mFront = mRear = -1;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void Display();
};
mQueue[mRear] = val;
}
if ( mFront == -1 )
mFront = 0;
}
if ( mFront == -1 )
cout << "Circular Queue is Empty";
else
{
return_value = mQueue[mFront];
if ( mFront == mRear )
mFront = mRear = -1;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
else
{
if ( mFront == MAX - 1 )
mFront = 0;
else
mFront++;
}
}
return return_value;
}
if ( mFront == -1 )
cout << "Circular Queue is Empty";
else
{
if ( mRear < mFront )
{
for ( i = mFront;i <= MAX - 1;i++ )
cout << mQueue[i] << " ";
else
{
for ( i = mFront;i <= mRear;i++ )
cout << mQueue[i] << " ";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
main()
{
CircularQueue oCircularQueue;
do
{
cout << "-----------Menu-------------\n";
cout << "1.Insertion2.Deletion3.Display4.Exit\n";
cout << "Enter Your Choice <1..4> ?";
cin >> get_choice;
switch ( get_choice )
{
case 1 :
cout << "Enter Element to Insert ?"; cin
>> get_element; oCircularQueue.Insertion
( get_element ); break;
case 2 :
get_element = oCircularQueue.Deletion();
cout << "Deleted Element :" << get_element << endl;
break;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 3 :
oCircularQueue.Display();
break;
}
Output
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
#include<stdlib.h>
#include <malloc.h>
struct Node
{
int Element;
Node *pLeft;
Node *pRight;
};
class BinarySearchTree
{
public:
void Insertion ( int, pNode & );
void Deletion ( int, pNode & );
int DeleteMinElement ( pNode & );
void Find ( int, pNode & );
pNode FindMinElement ( pNode );
pNode FindMaxElement ( pNode );
void MakeEmpty ( pNode & );
void Preorder ( pNode );
void Inorder ( pNode );
void Postorder ( pNode );
void FindLeftChild ( int, pNode & );
void FindRightChild ( int, pNode & );
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
};
else
{
if ( new_element < oRoot->Element )
Insertion ( new_element, oRoot->pLeft );
else
if ( new_element > oRoot->Element )
Insertion ( new_element, oRoot->pRight );
else
cout << "Element already Exits !";
}
}
if ( oRoot == NULL )
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
else
if ( ( oRoot->pLeft == NULL ) && ( oRoot->pRight == NULL ) )
{
oNode = oRoot;
free ( oNode );
oRoot = NULL;
}
else
if ( oRoot->pLeft == NULL )
{
oNode = oRoot;
free ( oNode );
oRoot = oRoot->pRight;
}
else
if ( oRoot->pRight == NULL )
{
oNode = oRoot;
oRoot = oRoot->pLeft;
free ( oNode );
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
else
oRoot->Element = DeleteMinElement ( oRoot->pRight );
}
if ( oRoot->pLeft == NULL )
{
result = oRoot->Element;
oRoot = oRoot->pRight;
return result;
}
else
return result;
}
if ( oRoot != NULL )
{
MakeEmpty ( oRoot->pLeft );
MakeEmpty ( oRoot->pRight );
oNode = oRoot;
free ( oNode );
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
oRoot = NULL;
}
}
else
{
return oRoot;
}
}
else
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return oRoot;
}
}
if ( x < oRoot->Element )
Find ( x, oRoot->pLeft );
else
if ( x > oRoot->Element )
Find ( x, oRoot->pRight );
else
cout << "Element Found !";
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Preorder ( oRoot->pRight );
}
}
Inorder ( oRoot->pLeft );
cout << oRoot->Element << "-->";
Inorder ( oRoot->pRight );
}
}
Postorder ( oRoot->pLeft );
Postorder ( oRoot->pRight );
cout << oRoot->Element << "-->";
}
}
else
if ( left_child < oRoot->Element )
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
cout << "Right child of " << right_child << "is " << oRoot-
>pRight->Element;
else
cout << "No Right Child !";
}
}
int main()
{
do
{
cout << "Binary Search Tree \n";
cout << "------------------------- \n ";
cout << "1.Insertion\n 2.Deletion\n 3.Find\n 4.Findmax\n 5.Findmin\n
6.Preorder\n 7.Inorder\n 8.Postorder\n 9.Leftchild\n 10.Rightchild\n 0.Exit
\n ";
cout << " \nEnter your choice :";
cin >> choice;
switch ( choice )
{
case 1:
cout << " 1.Insertion \n ";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 2:
cout << " 2.Deletion \n";
case 3:
cout << " 3.Find \n";
case 4:
if ( root == NULL )
cout << " Tree is empty";
else
{
max = oBst.FindMaxElement ( root );
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
break;
case 5:
if ( root == NULL )
cout << " Tree is empty";
else
{
min = oBst.FindMinElement ( root );
break;
case 6:
if ( root == NULL )
cout << " Tree is empty";
else
{
break;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 7:
cout << " 7.Inorder\n ";
if ( root == NULL )
cout << " Tree is empty";
else
{
break;
case 8:
if ( root == NULL )
cout << "Tree is empty";
else
{
break;
case 9:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ( root == NULL )
cout << "Tree is empty";
else
{
cout << "Enter the node for which the left child is to befound
: ";
cin >> left_child;
oBst.FindLeftChild ( left_child, root );
}
break;
case 10:
if ( root == NULL )
cout << " Tree is empty";
else
{
cout << "Enter the node for which the Right child is to be
found";
cin >> right_child;
oBst.FindRightChild ( right_child, root );
}
break;
case 0:
exit ( 0 );
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
cin >> c;
return 0;
}
Output
struct Node
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
int Element;
Node *pLeft;
Node *pRight;
};
class BinarySearchTree
{
public:
void Insertion ( int, pNode & );
void MakeEmpty ( pNode & );
void Preorder ( pNode );
void Inorder ( pNode );
void Postorder ( pNode );
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Inorder ( root->pLeft );
cout << root->Element << "-->";
Inorder ( root->pRight );
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ( root != NULL )
{
Postorder ( root->pLeft );
Postorder ( root->pRight );
cout << root->Element << "-->";
}
}
int main()
{
do
{
cout << "Binary Search Tree \n";
cout << "------------------------- \n ";
cout << "1.Insertion\n 2.Preorder\n 3.Inorder\n 4.Postorder\n 0.Exit \n
";
cout << " \nEnter your choice :";
cin >> choice;
switch ( choice )
{
case 1:
cout << " 1.Insertion \n ";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
case 2:
cout << " 2.Preorder \n";
if ( root == NULL )
cout << " Tree is empty";
else
{
break;
case 3:
cout << " 3.Inorder\n ";
if ( root == NULL )
cout << " Tree is empty";
else
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
break;
case 4:
if ( root == NULL )
cout << "Tree is empty";
else
{
break;
case 0:
exit ( 0 );
}
cin >> c;
}
while ( c == 'y' || c == 'Y' );
return 0;
}
Output:
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class PrimsAlgorithm
{
private:
// No of nodes
int mNumberOfNodes;
// Edges in the graph
int mGraphEdge[250][4];
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
public:
void Input();
int Findset ( int );
void Algorithm();
void Output();
};
void PrimsAlgorithm::Input()
{
cout << "*************************************************\n"
<< " Program implements the prims algorithm\n"
<< "*************************************************\n";
cout << "Enter the no. of nodes in the undirected weighted graph ::";
cin >> mNumberOfNodes;
mNumberOfEdges = 0;
cout << "Enter the weights for the following edges ::\n";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
cout << " < " << i << " , " << j << " > ::";
int w;
cin >> w;
if ( w != 0 )
{
mNumberOfEdges++;
mGraphEdge[mNumberOfEdges][1] = i;
mGraphEdge[mNumberOfEdges][2] = j;
mGraphEdge[mNumberOfEdges][3] = w;
}
}
}
{
cout << " < " << mGraphEdge[i][1] << " , " << mGraphEdge[i][2] << " >
::" << mGraphEdge[i][3] << endl;
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return 2;
return -1;
}
void PrimsAlgorithm::Algorithm()
{
mNumberOfTreeEdges = 0;
mSet1 = 1;
// Fixing Source Node
mSet1Array[1] = 1;
mSet2 = mNumberOfNodes - 1;
int i;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
if ( min > mGraphEdge[i][3] )
{
min = mGraphEdge[i][3];
edge1 = mGraphEdge[i][1];
edge2 = mGraphEdge[i][2];
edge3 = mGraphEdge[i][3];
p = i;
}
}
}
cout << " < " << edge1 << " , " << edge2 << " > " << endl;
mGraphEdge[l][1] = mGraphEdge[l+1][1];
mGraphEdge[l][2] = mGraphEdge[l+1][2];
mGraphEdge[l][3] = mGraphEdge[l+1][3];
}
mNumberOfEdges--;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ( Findset ( edge2 ) == 2 )
{
mSet1Array[mSet1] = edge2;
m = edge2;
}
else
if ( Findset ( edge1 ) == 2 )
{
mSet1Array[mSet1] = edge1;
m = edge1;
}
int x;
mSet2--;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void PrimsAlgorithm::Output()
{
cout << "\nThe selected edges are ::\n";
cout << " < " << mTreeEdge[i][1] << " , " << mTreeEdge[i][2] << " > ::"
<< mTreeEdge[i][3] << endl;
}
}
int main()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
PrimsAlgorithm oprims;
oprims.Input();
oprims.Algorithm();
oprims.Output();
return 0;
}
Output
b) Kruskal Algorithm
#include<iostream>
#include<conio.h>
class KruskalAlgorithm
{
int mNode1, mNode2, mUnvisited, mVisited, i, j, mNoOfNodes, mNoOfEdges;
int mMinimumValue, mMinimumCost, mCost[10][10];
public:
KruskalAlgorithm()
{
mNoOfEdges = 1;
mMinimumCost = 0;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void ReadGraph();
void mKruskal ( int cost[][10], int n );
};
void KruskalAlgorithm::ReadGraph()
{
cout << "enter the no. of vertix\n";
cin >> mNoOfNodes;
cout << "enter the adjacency matrix(cost)\n";
if ( mCost[i][j] == 0 )
mCost[i][j] = 999;
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
{
mMinimumValue = cost[i][j];
mNode1 = mUnvisited = i;
mNode2 = mVisited = j;
}
while ( gParent[mUnvisited] )
mUnvisited = gParent[mUnvisited];
while ( gParent[mVisited] )
mVisited = gParent[mVisited];
if ( mUnvisited != mVisited )
{
mNoOfEdges++;
cout << "\nedge(" << mNode1 << "->" << mNode2 << ")=" <<
mMinimumValue;
mMinimumCost += mMinimumValue;
gParent[mVisited] = mUnvisited;
}
main()
{
KruskalAlgorithm oKruskalAlgorithm;
oKruskalAlgorithm.ReadGraph();
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
Output
class DijkstraAlgorithm
{
private:
int mAdjMatrix[15][15];
int mPredecessor[15], mDistance[15];
//keep track of visited node
bool mMark[15];
int mSourceVertex;
int mNumOfVertices;
public:
/* Read number of vertices, source vertex and Adjacency Matrix*/
void ReadVertex();
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void Initialize();
int GetClosestUnmarkedNode();
void CalculateDistance();
void Output();
void PrintShortestPath ( int );
};
void DijkstraAlgorithm::ReadVertex()
{
cout << "Enter the number of vertices of the graph(should be > 0)\n";
cin >> mNumOfVertices;
cout << "To enter infinity enter " << INFINITY << endl;
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void DijkstraAlgorithm::Initialize()
{
for ( int i = 0;i < mNumOfVertices;i++ )
{
mMark[i] = false;
mPredecessor[i] = -1;
mDistance[i] = INFINITY;
}
mDistance[mSourceVertex] = 0;
}
int DijkstraAlgorithm::GetClosestUnmarkedNode()
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
return closest_unmarked_node;
}
void DijkstraAlgorithm::CalculateDistance()
{
Initialize();
int min_distance = INFINITY;
int closest_unmarked_node;
int count = 0;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
count++;
}
}
void DijkstraAlgorithm::Output()
{
for ( int i = 0;i < mNumOfVertices;i++ )
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
if ( i == mSourceVertex )
cout << ( char ) ( mSourceVertex + 97 ) << ".." << mSourceVertex;
else
PrintShortestPath ( i );
int main()
{
DijkstraAlgorithm oDijkstraAlgorithm;
oDijkstraAlgorithm.ReadVertex();
oDijkstraAlgorithm.CalculateDistance();
oDijkstraAlgorithm.Output();
return 0;
}
Output
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class BellFordAlgorithm
{
private:
int mNoOfNodes;
int mAdjacentMatrix[MAX][MAX];
int mStartVertex;
int mDistance[MAX];
int mPredecessor[MAX];
public:
void ReadGraph();
void Initialize();
void Update();
void Check();
void Algorithm();
};
void BellFordAlgorithm::ReadGraph()
{
cout << "Enter the no. of nodes in the graph ::";
cin >> mNoOfNodes;
cout << "Enter the adjacency matrix (cost)for the graph ::\n";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void BellFordAlgorithm::Initialize()
{
for ( int i = 1;i <= mNoOfNodes;i++ )
{
mDistance[i] = INFINITY;
mPredecessor[i] = 0;
}
mDistance[mStartVertex] = 0;
}
void BellFordAlgorithm::Update()
{
for ( int i = 1;i <= mNoOfNodes - 1;i++ )
{
for ( int u = 1;u <= mNoOfNodes;u++ )
{
for ( int v = 1;v <= mNoOfNodes;v++ )
{
if ( mAdjacentMatrix[u][v] != 0 )
{
if ( mDistance[v] > mDistance[u] + mAdjacentMatrix[u][v] )
{
mDistance[v] = mDistance[u] + mAdjacentMatrix[u][v];
mPredecessor[v] = u;
}
}
}
}
}
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void BellFordAlgorithm::Check()
{
for ( int u = 1;u <= mNoOfNodes;u++ )
{
for ( int v = 1;v <= mNoOfNodes;v++ )
{
if ( mAdjacentMatrix[u][v] != 0 )
{
if ( mDistance[v] > mDistance[u] + mAdjacentMatrix[u][v] )
{
cout << "does not exist's ";
return;
}
}
}
}
cout << "****** The final paths and the distacnes are ******\n\n";
while ( mPredecessor[j] != 0 )
{
arr[k] = mPredecessor[j];
k++;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
j = mPredecessor[j];
}
cout << "distance is " << mDistance[i] << endl << endl << endl;
}
}
void BellFordAlgorithm::Algorithm()
{
ReadGraph();
Initialize();
Update();
Check();
}
main()
{
BellFordAlgorithm oBellFordAlgorithm;
oBellFordAlgorithm.Algorithm();
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
class FloydsWarshallAlgorithm
{
int mNoOfNodes;
int mPathMatrix[10][10];
int mAdjacencyMatrix[10][10];
int mGraphCost[10][10];
public:
void ReadGraph();
void PathMatrix();
void Algorithm();
void Display();
};
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
void FloydsWarshallAlgorithm::ReadGraph()
{
int i, j, k;
cout << "*********Floyds-Warshall Algorithm ***********";
cout << "Enter the no. of nodes in the graph :";
cin >> mNoOfNodes;
cout << "Enter the adjacency matrix :";
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
mPathMatrix[i][j] = mAdjacencyMatrix[i][j];
}
}
}
void FloydsWarshallAlgorithm::Display()
{
for ( int i = 1;i <= mNoOfNodes;i++ )
{
for ( int j = 1;j <= mNoOfNodes;j++ )
{
cout << mPathMatrix[i][j] << " ";
}
void FloydsWarshallAlgorithm::PathMatrix()
{
int i, j, k;
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
}
}
void FloydsWarshallAlgorithm::Algorithm()
{
int i, j, k;
mPathMatrix[i][j] = mGraphCost[i][j];
}
}
else
{
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
main()
{
FloydsWarshallAlgorithm oFloydsWarshallAlgorithm;
oFloydsWarshallAlgorithm.ReadGraph();
oFloydsWarshallAlgorithm.PathMatrix();
cout << "Path matrix is :\n";
oFloydsWarshallAlgorithm.Display();
oFloydsWarshallAlgorithm.Algorithm();
cout << "All pair shortest path matrix is :\n";
oFloydsWarshallAlgorithm.Display();
}
Output
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com
WWW.VIDYARTHIPLUS.COM
WWW.VIDYARTHIPLUS.COM V+ TEAM
www.Vidyarthiplus.com