Sei sulla pagina 1di 289

CS6311 - PROGRAMMING & DATA STRUCTURES

LABORATORY - II
1. C++ program for Constructors
2. C++ program for Friend Function and Friend class
a) Program for friend function
b) program for friend class
3. C++ Program for Inheritance
a) Single Inheritance
b) Multiple Inheritance
c) Multi Level Inheritance
d) Hybrid Inheritance
4. C++ program for Polymorphism & Function Overloading.
a) Polymorphism
b) Function Overloading
5. C++ program for Virtual Functions
6. Overloading unary and binary operator using Member function and Non-member function
7. Class and Function template
a) Function Template
Displaying greatest value using function
template b) Class Template
Displaying greatest number using class template.
8. Exception Handling
a) Division by zero
b) Division by zero using function
c) User defined exception handling

d) Out of range Exceptions


e) Program for Arithmetic exception handling
9. STL Concepts
a) Container
STL Container-vector operators
STL Container-vector, swap()
Program for Vector
b) Allocator
c) Iterator
Iterator - a list container
Iterator - a set container
Iterator - a multi-set container
Iterator - a map container
Iterator - a multi-map container
d) Function Adaptors
10. Filestream Concepts
a) Program to write a text in the file
b) Program to read data from text file and display it
c) Program to count number of characters from out.txt.
d) Program to count number of words from out.txt
e) Program to count number of lines in the file
f) Program to copy contents of one file to another file.
g) Binary file(Write mode)
h) Binary file(Read mode)
i) Reading from and writing the personal details into the file using getline function
j) Reading from and writing into the file

11) Application of Stack & Queue


a) Stack Implementation
b) Queue Implementation
c) Infix to Postfix Conversion:
d) Evaluation of Postfix Expression
e) Circular Queue Application of queue
12) Implementation of Binary search tree
13. Implementation of Tree Traversal
14. Minimum Spanning Tree
a) Prim's Algorithm
b) Kruskal Algorithm
15. Shortest Path Algorithm
a) Dijkstra's Algorithm
b) Bellman Ford Algorithm
c) Floyds Warshall Algorithm

1. C++ program for Constructors


#include<iostream>
#include<string.h>
using namespace std;
//class name
class StudentDetails
{
//access specifier
private:
//declaration of member variables
int mStudentmarks;
char
mStudentgrade;
char*
pStudentname;

int

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

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

char* first = "Cherry " ;


char* second = " Merry ";

cout << "Record of student 1:" << endl;


//second object created for the class
StudentDetails oNameStudent1(first);
oNameStudent1.StudentName();
oStudent1.StudentMark();
cout << "Record of student 2:" << endl;
StudentDetails oNameStudent2(second);
oNameStudent2.StudentName();
oStudent2.StudentMark();
cout << " highest marks and grade of the class \n";
oHighestMark.StudentMark();
}
Output

2. C++ program for Friend Function and Friend class


a) Program for friend function
#include<iostream>
#include<string>

using namespace std;


//class
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;
}
// Declare the two functions friends.
friend int addition(friends input); friend
int subtraction(friends input);
};
// Function one
int addition(friends input)
{
// addition operation performed
return int(input.mVar1 + input.mVar2);

}
// 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:

b) program for friend class


#include <iostream>
using namespace std;
class Square;
class Rectangle
{
int width, height;
public:
int area ()
{
return ( width * height );
}
void convert ( Square a );
};
class Square
{
friend class Rectangle;
private: int
side;
public:
Square ( int a ) : side ( a ) {}
};
void Rectangle::convert ( Square a )
{
width = a.side;
height = a.side;
}
int main ()
{
Rectangle rect; Square
sqr ( 4 ); rect.convert
( sqr ); cout <<
rect.area(); return 0;
}
Output

3. C++ Program for Inheritance

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

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

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 );
}
};
/* Rectangle class is derived from classes Area and Perimeter. */ class
Rectangle : private Area, private Perimeter
{
private:
float length, breadth;
public:

Rectangle() : length ( 0.0 ), breadth ( 0.0 ) { } void


get_data( )
{
cout << "Enter length: ";
cin >> length;
cout << "Enter breadth: ";
cin >> breadth;
}
float area_calc()
{
/* Calls area_calc() of class Area and returns it. */
return Area::area_calculate ( length, breadth );
}
float peri_calc()
{
/* Calls peri_calc() function of class Perimeter and returns it. */
return Perimeter::peri_calculate ( length, breadth );
}
};
int main()
{
//object created Rectangle
oRectangle;
oRectangle.get_data();
cout << "Area = " << oRectangle.area_calculate();
cout << "\n Perimeter = " << oRectangle.peri_calculate();
return 0;
}
Output

c) Multi Level Inheritance


#include<iostream>
using namespace
std;
//base class
class top
{
public :
int a;
void getdata()
{
cout << "\n\nEnter the Value :\t"; cin
>> a;
}
};
//First level inheritance // class
middle is derived_1 class
middle : public top
{
public:
int b;
void square()
{
getdata();
b = a * a;
cout << "\n\nSquare Is :" << b;
}
};
//Second level inheritance //
class bottom is derived_2 class
bottom : public middle
{
public:
int c;
void cube()
{
square();
c = b * a;
cout << "\n\nCube :\t" << c;
}
};

int main()
{
bottom
b1;
b1.cube();
}

Output

d) Hybrid Inheritance
#include<iostream>
#include<string.h>
using namespace std;
//base class name
class StudentResult
{
int mStud_Rollno;
public:
//member function of base class
void GetRollnumber()
{
cout << "Enter Roll No:";
cin >> mStud_Rollno;
}
//member function of base class
void PutRollnumber()

{
cout << "\n\n\tRoll No:" << mStud_Rollno << "\n";
}
};
//Deriving class Test from base class Student result
class Test : virtual public StudentResult
{
public:
int mSubject1,mSubject2;
/ member function of derived class
void GetSubjectmarks()
{
cout << "Enter Marks\n";
cout << "subject1:"; cin
>> mSubject1;
cout << "subject2:";
cin >> mSubject2;
}
/ member function of derived class
void PutSubjectmarks()
{
cout << "\tMarks Obtained\n";
cout << "\n\tsubject1:" << mSubject1;
cout << "\n\tsubject2:" << mSubject2;
}
};
//Derived class2 from base class

class Sports:public virtual StudentResult


{
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;
}
};
/*deriving a class from 2 derived classes*/
class Result : public Test, public Sports
{
int mTotal;
public:
//derived class function
void mDisplay()
{
mTotal = mSubject1 + mSubject2 + mScore;
PutRollnumber();
PutSubjectmarks();

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:

4. C++ program for Polymorphism & Function Overloading.


a) Polymorphism
#include<iostream>
using namespace std;

//class
class Shape
{
protected:
//member variable
double mLength;
double mBreath;
public:
//Member function
void Getdata(double mLength1,double mBreath1)
{
mLength=mLengt
h1;
mBreath=mBreat
h1;
}
virtual void display()
{
}

};
//Derived class 1
class triangle:public Shape
{
double Var_T;
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

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>
using namespace std;

//class
class PrintData
{
public:
//member function to get integer value
void Print(int mIntValue)
{
cout << "Printing int: " << mIntValue << endl;
}
//member function to get double value
void Print(double mDoubnleValue)
{
cout << "Printing float: " << mDoubnleValue << endl;
}
//member function to get character
void Print(char* mCharacterValue)
{
cout << "Printing character: " << mCharacterValue << 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:

5. C++ program for Virtual Functions


#include <iostream>
using namespace
std;
// abstract base class
class Shape
{
protected: // attribute section int
mWidth;
int mHeight;
int mResult;
public: // behavior section
void setVar(int Width,int Height)
{
mWidth = Width;
mHeight= Height;
}
virtual void area()
{
// virtual function
cout<< "shape drawn";
}
int getresult()
{
return mResult;
}
};
// add class inherits from base class
class rectangle: public Shape
{

public:
void area()
{
mResult = mWidth*mHeight;
}
};
//sub class inherit base class class
triangle: public Shape
{

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: ";
while (cin >> Length >> Breath)
{
oShape = &oRectangle; oShape>setVar( Length , Breath );
//area of rectangle process, even though call is on pointer to
base(shape)!
oShape->area();
cout << "\nArea of rectangle = " << oShape->getresult();
oShape = &oTriangle;
oShape->setVar( Length , Breath );
//triangle process, even though call is on pointer to base!
oShape->area();
cout << "\nArea of triangle = " << oShape->getresult() << endl;
}
return 0;
}
Output

6. Overloading unary and binary operator using Member


function and Non-member function
#include<iostream>
using namespace std;
class ComplexOperations
{
// Access specifies
private:
// Declaration of member variables
float mRealnumber;
float mImaginarynumber;
public:
ComplexOperations()
{
mRealnumber = mImaginarynumber = 0.0;
}
ComplexOperations ( int real, int imaginary )

{
mRealnumber = real;
mImaginarynumber = imaginary;
}
ComplexOperations ( double real, double imaginary )
{
mRealnumber = real;
mImaginarynumber = imaginary;
}
friend istream & operator >> ( istream& , ComplexOperations& );
friend ostream & operator << ( ostream& , ComplexOperations& );
ComplexOperations operator+ ( ComplexOperations );
ComplexOperations operator- ( ComplexOperations );
ComplexOperations operator* ( ComplexOperations );
ComplexOperations operator/ ( ComplexOperations );
};
istream& operator >> ( istream& input , ComplexOperations& oComplex )
{
cout

<< "Real Part:";

input >> oComplex.mRealnumber;


cout

<< "Imaginary Part:";

input >> oComplex.mImaginarynumber;

return input;
}

ostream& operator << ( ostream& output , ComplexOperations& oComplex )//


Defining non-member function
{
if ( oComplex.mImaginarynumber < 0 )
output << oComplex.mRealnumber << oComplex.mImaginarynumber << "i";
else
output << oComplex.mRealnumber << "+" <<
oComplex.mImaginarynumber <<
"i";
return output;
}
// Defining member function
ComplexOperations ComplexOperations::operator+ ( ComplexOperations
oComplex)
{
ComplexOperations oAddition;
oAddition.mRealnumber = mRealnumber + oComplex.mRealnumber;
oAddition.mImaginarynumber = mImaginarynumber +
oComplex.mImaginarynumber;
return oAddition;
}
ComplexOperations ComplexOperations::operator-(ComplexOperations oComplex

ComplexOperations oSubtraction;
oSubtraction.mRealnumber = mRealnumber - oComplex.mRealnumber;
oSubtraction.mImaginarynumber =mImaginarynumberoComplex.mImaginarynumber;
return oSubtraction;
}
ComplexOperations ComplexOperations::operator*(ComplexOperations oComplex
{
ComplexOperations oMulti;
oMulti.mRealnumber = mRealnumber * oComplex.mRealnumber mImaginarynumber
*

oComplex.mImaginarynumber;
oMulti.mImaginarynumber = mRealnumber * oComplex.mImaginarynumber

+ mImaginarynumber * oComplex.mRealnumber;
return oMulti;
}
ComplexOperations ComplexOperations::operator/ ( ComplexOperations oComplex
)
{
ComplexOperations oDivision;
float result_of_complexoperations;
result_of_complexoperations = oComplex.mRealnumber *
oComplex.mRealnumber + oComplex.mImaginarynumber *
oComplex.mImaginarynumber;
oDivision.mRealnumber = ( mRealnumber * oComplex.mRealnumber +
mImaginarynumber * oComplex.mImaginarynumber )/result_of_complexoperations;

oDivision.mImaginarynumber = ( mImaginarynumber * oComplex.mRealnumber


-

mRealnumber * oComplex.mImaginarynumber )/result_of_complexoperations;


return oDivision;

}
int main()
{
ComplexOperations oNumberOne, oNumberTwo, oNumberThree;
cout
cin
cout
cin
cout

<<

"complex number 1: ";

>> oNumberOne;
<< "complex number 2: ";
>> oNumberTwo;
<< "complex numbers are:";

cout << "1st:" << oNumberOne;


"\n2nd:" <<
cout << oNumberTwo;
oNumberThree = oNumberOne + oNumberTwo;
cout

<< "\nAddition is:" << oNumberThree;

oNumberThree = oNumberOne - oNumberTwo


cout

<< "\nSubtraction is:" << oNumberThree;

oNumberThree =
oNumberOne

* oNumberTwo;

cout << "\n Multiplication is:"


<< oNumberThree;
oNumberThree =
oNumberOne
/ oNumberTwo
cout

<< "\n Division is:"

return 0;

<< oNumberThree;

}
Output

7. Class and Function template


a) Function Template
Displaying greatest value using 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
retur number_one <
n
number_two
}
int main ()

? number_two : number_one;

{
/

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;
Max(double_number_one,
cout << "Double Result:"
<<
double_number_two);
cout << "Enter string values";
cin

>> string_word_one >> string_word_two;

cout << "String Result:"


return 0;
}

Output:

<<

Max(string_word_one, string_word_two);

b) Class Template
Displaying greatest number using 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 ()

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

cout<<"Enter the value of a:";


cin>>number_one;
cout<<"Enter the value of b:";
cin>>number_two;
cout<<"Enter the value of c:";
cin>>number_three;
// try function
try
{
/*Check whether the difference of two numbers not equal to zero*/
if ((number_one-number_two)!=0)
{
// Get the division values
number_four=number_three/(number_onenumber_two); cout<<"Result is:"<< number_four;
}
else
{
// throws the value
throw(number_onenumber_two);
}
}
// catch the integer number
catch (int int_Numberone)
{
cout<<"Answer is infinite because a-b is:"<<int_Numberone;
}
return 0;
}
Output:

b) Division by zero using function


#include <iostream>
using namespace std;
//Function definition
double Division(int Number_one, int Number_two)
{
// chexk the number equals to zero if
( Number_two == 0 )

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

c) User defined exception handling


#include <iostream>

using namespace std;


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

cout << "\n";


return 0;

Output:

d) Out of range Exceptions


#include <iostream>
using namespace std;
class OutOfRangeException {};
/*
* 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
*/
float calculateAverage ( int mark_one, int mark_two, int mark_three, int
mark_four )
{
if ( ( mark_one < 0 || mark_one > 100 ) )
throw OutOfRangeException();
if ( mark_two < 0 || mark_two > 100 )
throw OutOfRangeException();
if ( mark_three < 0 || mark_three > 100 )
throw OutOfRangeException();
if ( mark_four < 0 || mark_four > 100 )
throw OutOfRangeException();

return ( mark_one + mark_two + mark_three + mark_four ) / 4.0;


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

e) Program for Arithmetic exception handling


#include <iostream>
#include <string.h>
#include<stdlib.h>
using namespace std;
int main()
{
// Variables declaration
char Number1[40], Number2[40];
double Operand1, Operand2, Result;

char Operator;
// Request two numbers from the user
cout << "This program allows you to perform a division of two numbers\n";
cout << "To proceed, enter two numbers\n";
try
{
cout << "First Number: ";
cin >> Number1;
cout << "Operator: "; cin
>> Operator;
cout << "Second Number:
"; cin >> Number2;
/ Examine each character of the first operand
/ to find out if the user included a non-digit in the number for
(int i = 0; i < strlen(Number1); i++)
if ( (!isdigit(Number1[i])) && (Number1[i] != '.') )
// Send the error as a string
throw Number1;
Operand1 = atof(Number1);
// Do the same for the second number entered for
(int j = 0; j < strlen(Number2); j++)
if ( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Send
the error as a string
throw
Number2; Operand2 =
atof(Number2);

/ Make sure the user typed a valid operator if


(Operator != '+' && Operator != '-' &&
Operator != '*' && Operator != '/')
throw Operator;
/ Find out if the denominator is 0
if (Operator == '/') if
(Operand2 == 0)
throw 0;
// Perform an operation based on the user's choice
switch (Operator)
{
case '+':
Result = Operand1 +
Operand2; break;
case '-':
Result = Operand1 - Operand2;

break;
case '*':
Result = Operand1 *
Operand2; break;
case '/':
Result = Operand1 / Operand2;
break;
}
// Display the result of the operation
cout << "\n" << Operand1 << " " << Operator << "
" << Operand2 << " = " << Result << "\n\n";

}
catch (const int n)
{
cout << "\n Bad Operation: Division by " << n << " not allowed\n\n";
}
catch (const char n)
{
cout << "\n Operation Error: " << n << " is not a valid operator\n\n";
}
catch (const char *BadOperand)
{
cout << "\n Error: " << BadOperand << " is not a valid number\n\n";
}
return 0;
}

Output:

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

for ( i =

1; i <= size_three; ++i )

vec3.push_back ( i );
// print all elements separated by a space
for ( i =

0; i < vec3.size(); ++i )

cout << vec3[i] << ' ';


cout << endl << endl;
// more operations
cout << "Operation: vec1 != vec2;" << endl;
if ( vec1
cout
<<

!= vec2 )
"vec1 vector and vec2 vector is not equal." << endl;

else
cout << "vec1 vector and vec2 vector is equal." << endl;
cout << "\n Operation: vec1 == vec3;" << endl;
if ( vec1

== vec3 )

cout << "vec1 vector and vec3 vector is equal." << endl;
else
cout
<<

"vec1 vector and vec3 vector is not equal." << endl;

cout << "\n Operation: vec1 < vec2;" << endl;


if ( vec1
cout
<<
else
cout
<<

< vec2 )
"vec1 vector less than vec2 vector." << endl;

"vec1 vector is not less than vec2 vector." << endl;

cout << "\n Operation: vec2 > vec1;" << endl;


if ( vec2

> vec1 )

cout << "vec2 vector greater than vec1 vector." << endl;
else
cout
<<

"vec2 vector is not greater than vec1 vector." << endl;

cout << "\n Operation: vec2 >= vec1;" << endl;


if ( vec2
cout
<<
else
cout
<<

>= vec1 )
"vec2 vector greater or equal than vec1 vector." << endl;

"vec2 vector is not greater or equal than vec1 vector." << endl;

cout << "\n Operation: vec1 <= vec2;" << endl;

if ( vec1 <= vec2 )


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

STL Container-vector, swap()


#include <vector>
#include <iostream>
using namespace std;
int main()
{
unsigned int i;
// vector container for integer elements
vector<int> vector_one, vector_two;
int start_one, start_two; int
size_one, size_two;

cout << "Enter the range for vector one";


cin >> start_one >> size_one;

cout << "Enter the range for vector two";


cin >> start_two >> size_two;
// print vector data
cout << "vector_one data: ";
// append elements with values
for ( i = start_one; i <= size_one; ++i )
vector_one.push_back ( i );
// print all elements separated by a space for (
i = 0; i < vector_one.size(); ++i )

cout << vector_one[i] << ' ';


cout << endl;
cout << "vector_two data: ";
// append elements with values 11 to 20 for
( i = start_two; i <= size_two; ++i )
vector_two.push_back ( i );
// print all elements separated by a space for (
i = 0; i < vector_two.size(); ++i )

cout << vector_two[i] << ' ';


cout << endl;
// do the swapping
cout << "Operation:Swapping two vectors" << endl << endl;
vector_one.swap ( vector_two );
cout << "vector_one data: ";
for ( i = 0; i < vector_one.size(); ++i )
cout << vector_one[i] << ' ';
cout << endl;
cout << "vector_two data: ";
for ( i = 0; i < vector_two.size(); ++i )
cout << vector_two[i] << ' ';
cout << endl;
cout << "The number of elements in vector_one = " << vector_one.size() <<
endl;

cout << "The number of elements in vector_two = " << vector_two.size() <<
endl;
cout << endl;
return 0;
}
Output

Program for Vector


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
using namespace
std; int main()
{
// create empty vector for strings
vector <string> sentence;
string str;
// reserve memory for five elements to avoid reallocation
sentence.reserve ( 5 );

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

cout << " size():


cout << " capacity(): "

<< sentence.max_size() <<


endl;
<<
" << sentence.size()
endl;
<< 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

copy ( sentence.begin(), sentence.end(),


ostream_iterator<string> ( cout, " " ) );
cout
<<

endl;

// print ``technical data'' again


<< sentence.max_size() <<
cout << " max_size(): " endl;
<<
cout << " size():
" << sentence.size()
endl;
cout << " capacity(): "

<< sentence.capacity() << endl;

int position_one, position_two;


cout << "Enter the positions to swap two string"; cin
>> position_one >> position_two;
// swap second and fourth element
swap ( sentence[position_one-1], sentence[position_two-1] );
cout << "After swapping";
copy ( sentence.begin(), sentence.end(),
ostream_iterator<string> ( cout, " " ) );
cout << endl;
}
Output

b) Allocator
#include <iostream>

#include
<algorithm>

#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 )
{}
bool operator< ( Account const& account ) const
{
return credit < account.credit;
}
int potential_credit() const
{
return credit + potential_credit_transfer;
}
std::string const& owner() const
{
return owner_name;
}
};
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();
}

};
int main()
{
Account account1 ( "Dennis Ritchie", 1000, 250 ), account2 ( "Steeve Jobs", 500,
10000 ),
result_comparison;
);

result_comparison = std::min ( account1, account2, CompareAccountCredit()

std::cout << "min credit of account is : " + result_comparison.owner() <<


std::endl;
result_comparison = std::min ( account1, account2,
CompareAccountPotentialCredit() );
std::cout << "min potential credit of account is : " +
result_comparison.owner() << std::endl;
return 0;
}
Output

c) Iterator
Iterator - a list container
#include <iostream>
#include <list>
using namespace
std;
int main()
{

/ lst, list container for character elements


list<char> lst;
/ append elements from 'A' to 'Z' to the list lst container for (
char chs = 'A'; chs <= 'Z'; ++chs )
lst.push_back ( chs );
/ iterate over all elements and print, separated by space
list<char>::const_iterator pos;
for ( pos = lst.begin(); pos != lst.end(); ++pos )
cout << *pos << ' ';
cout << endl;
return 0;

Output:

Iterator - a set container


#include
<iostream>
#include <set>
using namespace std;
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 postdecrement...
for ( pos = tst.begin(); pos != tst.end(); ++pos )
cout << *pos << ' ';
cout << endl;
return 0;
}

Output

Iterator - a multi-set container


#include
<iostream>
#include <set>
using namespace std;
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 postdecrement...
for ( pos = tst.begin(); pos != tst.end(); ++pos )
cout << *pos << ' ';
cout << endl;
return 0;
}
Output

Iterator - a map container


#include
<iostream>
#include <map>

#include <string>
using namespace
std;
int main()
{
/ type of the collection
map<int, string> mp;
/ set container for int/string values insert some elements in arbitrary order
/ notice a value with key 1...
mp.insert ( make_pair ( 5, "learn" ) ); mp.insert
( make_pair ( 2, "map" ) ); mp.insert
( make_pair ( 1, "Testing" ) ); mp.insert
( make_pair ( 7, "tagged" ) ); mp.insert
( make_pair ( 4, "strings" ) ); mp.insert
( make_pair ( 6, "iterator!" ) ); mp.insert
( make_pair ( 1, "the" ) ); mp.insert ( make_pair
( 3, "tagged" ) );
// iterate over all elements and print, element member second is the value
map<int, string>::iterator pos;
for ( pos = mp.begin(); pos != mp.end(); ++pos )
cout << pos->second << ' ';
cout << endl;
return 0;

}
Output

Iterator - a multi-map container


#include <iostream>
#include <map>
#include <string>
using namespace
std;
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" ) );

mmp.insert ( make_pair ( 1, "Testing" ) );


mmp.insert ( make_pair ( 7, "tagged" ) );
mmp.insert ( make_pair ( 4, "strings" ) );
mmp.insert ( make_pair ( 6, "iterator!" ) );
mmp.insert ( make_pair ( 1, "the" ) ); mmp.insert
( make_pair ( 3, "tagged" ) );
// iterate over all elements and print, element member second is the value
multimap<int, string>::iterator pos;
for ( pos = mmp.begin(); pos != mmp.end(); ++pos
) cout << pos->second << ' ';
cout << endl;
return 0;

}
Output

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};
const int N = sizeof ( array ) / sizeof ( int );
// for_each() returns function object after being applied to each element
PrintData<int> f = std::for_each ( array, array + N, PrintData<int> (
std::cout ) );

std::cout << std::endl << std::endl << f.count_ << " objects printed." <<
std::endl;
return 0;
}
Output

10. Filestream Concepts


a) Program to write a text in the file
#include<iostream>
#include<fstream>
using namespace std;
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:

b) Program to read data from text file and display it


#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
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:

c) Program to count number of characters from out.txt.


#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
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*/

while ( !oFileinput.eof() )
{
/

Read characters from the text file

oFileinput.get ( char_text );
/

Increment the count values

int_count++;
}
// Display number of characters in text file
cout << "Number of characters in file is " << int_count;
//Close the text file opened in read mode
oFileinput.close();
return 0;
}
Output:

d) Program to count number of words from out.txt


#include<iostream>

#include<fstream>
#include<conio.h>
using namespace std;
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++;
}
// 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:

e) Program to count number of lines in the file


#include<iostream>
#include<fstream>
#include<conio.h>
using namespace std;
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++;
}
// 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

f) Program to copy contents of one file to another file.


#include<iostream>
#include<fstream>
#include<conio.h>

using namespace std;


int main()
{
// Create object to read input values
ifstream oFileinput;
/

Open the text file in read mode

oFileinput.open ( "out.txt" );
/

Create object to display output values

ofstream oFileoutput;
/

Open the text file in write mode

oFileoutput.open ( "sample.txt" );
/

Character declaration

char char_text;
/* Read the character until the file reach end of file*/
while ( !oFileinput.eof() )
{
// Read characters from the "out.txt"
oFileinput.get ( char_text );
// Write characters to "sample.txt"
oFileoutput << char_text;

//Close the text file opened in read mode


oFileinput.close();
return 0;
}
Output:

g) Binary file(Write mode)


#include<iostream>
#include<fstream>
using namespace std;
struct StudentDetails
{
int RollNo; char
Name[30];
char Address[40];
};
void ReadStudentDetails ( StudentDetails& TempStud )
{
cout << "\n Enter Roll No:";
cin >> TempStud.RollNo;

cout << "\n Enter Name:";


cin >> TempStud.Name;

cout << "\n Enter Address:";


cin >> TempStud.Address;
cout << "\n";
}
int main()
{
struct StudentDetails BE_Student_Output;
ofstream BE_StudFile_Output;
BE_StudFile_Output.open ( "BE.dat", ios::out | ios::binary | ios::trunc );
if ( !BE_StudFile_Output.is_open() )
{
cout << "File cannot be opened \n";
}
char Continue = 'Y';
do
{
ReadStudentDetails ( BE_Student_Output );
BE_StudFile_Output.write ( ( char* ) &BE_Student_Output, sizeof (
struct StudentDetails ) );
if ( BE_StudFile_Output.fail() )
{
cout << "file write failed";
}

else
{
cout << "Do you want to continue Y/N:";
cin >> Continue;
}
}
while ( Continue != 'N' );
BE_StudFile_Output.close();
return 0;
}

Output

h) Binary file(Read mode)


#include<iostream>
#include<fstream>
using namespace std;
// Declaring the structure variables
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()
{

struct StudentDetails BE_Student_Input;


ifstream BE_StudFile_Input ( "BE.dat", ios::out | ios::binary );
while ( !BE_StudFile_Input.eof() )
{
BE_StudFile_Input.read ( ( char* ) &BE_Student_Input, sizeof ( struct
StudentDetails ) );
if ( BE_StudFile_Input.fail() )
{
break;
}
WriteStudentDetails ( BE_Student_Input );
}
BE_StudFile_Input.close();
return 0;
}
Output:

i) Reading from and writing the personal details into the file using
getline function
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char Personal_data[100];
// open a file in write mode.
ofstream oFileoutput;
oFileoutput.open ( "personalfile.dat" );
cout << "Writing to the file" << endl;
cout << "Enter your name: "; cin.getline
( Personal_data, 100 );
// write input data into the file.
oFileoutput << Personal_data << endl;
cout << "Enter your age: ";
cin >> Personal_data;
cin.ignore();

again write input data into the file.

oFileoutput << Personal_data << endl;


/

close the opened file.

oFileoutput.close();
// open a file in read mode.

ifstream oFileinput;
oFileinput.open ( "personalfile.dat" );
cout << "Reading from the file" << endl;
oFileinput >> Personal_data;

write the data at the screen.

cout << Personal_data << endl;

again read the data from the file and display it.

oFileinput >> Personal_data;


cout << Personal_data << endl;
// close the opened file.
oFileinput.close();

return 0;
}
Output

j) Reading from and writing into the file


#include<fstream.>
#include<stdio.h>
#include<ctype.h>
#include<string>
#include<iostream>
using namespace std;
int main()
{
char txt_file_data,file_ASCII_result; char
char_filename[10];
ofstream oFileoutput;
cout<<"Enter File Name:";
cin>>char_filename;
oFileoutput.open(char_filename);
//write contents to file
cout<<"Enter the text(Enter # at end)\n";
while ((txt_file_data=getchar())!='#')
{

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

11) Application of Stack & Queue


a) Stack Implementation
#include<iostream>
using namespace std;
class StackImplementation
{
int
mMaximumsize;
int

mTopofstack;

int *pTemp;
public :
StackImplementation ( int );
void Push ( int );
int Pop();
int IsEmpty();
int IsFull();
void Display();

~StackImplementation();
};
StackImplementation::StackImplementation ( int maxsize )
{
mMaximumsize =
maxsize; mTopofstack =
-1;

pTemp = new int ( mMaximumsize );


}
void StackImplementation::Push ( int get_value )
{
if ( IsFull() )
cout << "Stack is full" << endl;
else
{
mTopofstack++;
pTemp[mTopofstack] = get_value;
}
}
int StackImplementation ::Pop()
{
if ( IsEmpty() )
return -1;
else
{
int x = pTemp[mTopofstack];
mTopofstack--;
return x;
}
}

int StackImplementation::IsEmpty()
{
if ( mTopofstack == -1 )
return 1;
else
return 0;
}
int StackImplementation :: IsFull()
{
if ( mTopofstack == mMaximumsize - 1 )
return 1;
else
return 0;
}
void StackImplementation::Display()
{
if ( IsEmpty() )
cout << "Empty list" << endl;
else
{
cout << "The element in stack are:\n";
for ( int i = mTopofstack;i >= 0;i-- )
cout << pTemp[i] << " ";
cout << endl;
}
}
StackImplementation::~StackImplementation()
{

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;
while ( get_option < 4 )
{
switch ( get_option )
{
case 1:
cout << "Enter element" << endl;
cin >> get_value;
oStack.Push ( get_value );
break;

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();
cin >> get_option;
}
return 0;
}
Output

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;
}
void Enqueue ( int x )
{
if ( mRear > 4 )
{
cout << "Queue is overflow";
mFront = mRear = -1;
return;
}

mQueueArray[++mRear] = x;
}
void Dequeue()
{
if ( mFront == mRear )
{
cout << "Queue is underflow";
return;
}
cout << "Dequeue:" << mQueueArray[++mFront];
}
void Display()
{
if ( mRear == mFront )
{
cout << "Queue is
empty"; return;
}
cout << "Queue";
for ( int i = mFront + 1;i <= mRear;i++ )
cout << "\t" << mQueueArray[i];
}
};
main()
{
int get_choice, get_no_of_elements, get_element;

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:
cout << "Enter the number of elements:";
cin >> get_no_of_elements;
for ( int i = 0;i < get_no_of_elements;i++ )
{
cout << "Enter a number";
cin >> get_element;

oQueue.Enqueue ( get_element );
}
break;
case 2:
oQueue.Dequeue();
break;
case 3:
oQueue.Display();
break;

case 4:
exit ( 0 );
break;

default:
cout << "Invalid";
break;
}
}
return ( 0 );
}
Output:

c) Infix to Postfix Conversion:


#include<iostream>
#include<conio.h>
using namespace std;

class StackOperation
{
public:
char mStack[50];
int mTopOfStack;
StackOperation()
{
mTopOfStack = -1;
}
void Push ( char symbol )
{
if ( IsStackFull() )
{
cout << "\nStack overflow:\n";
}
else
{
mTopOfStack = mTopOfStack + 1;
mStack[mTopOfStack] = symbol;
}
}
char Pop()
{
if ( IsStackEmpty() )
// Return value '#' indicates stack is empty
return ( '#' );
else
return ( mStack[mTopOfStack--] );
}
int IsStackEmpty()
{

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;
}
int WhiteSpace ( char symbol )
{
if ( symbol == ' ' || symbol == '\t' || symbol == '\0' )
return 1;
else
return 0;

}
void ConvertToPostfix()
{
StackOperation oStackOperation;
int l, precedence, p;
char Entry1, Entry2;
p = 0;
for ( int i = 0;infix[i] != '\0';i++ )
{
Entry1 = infix[i];
if ( !WhiteSpace ( Entry1 ) )
{
switch ( Entry1 )
{
case '(':
oStackOperation.Push ( Entry1 );
break;
case ')':
while ( ( Entry2 = oStackOperation.Pop() ) != '(' )
postfix[p++] = Entry2;
break;
case '+':
case '-':
case '*':

case '/':
if ( !oStackOperation.IsStackEmpty() )
{
precedence = PrecedenceSymbol ( Entry1 );
Entry2 = oStackOperation.Pop();
while ( precedence <= PrecedenceSymbol ( Entry2 ) )
{
postfix[p++] = Entry2;
if ( !oStackOperation.IsStackEmpty() )
Entry2 = oStackOperation.Pop();
else
break
;
}
if ( precedence > PrecedenceSymbol ( Entry2 ) )
oStackOperation.Push ( Entry2 );
}
oStackOperation.Push ( Entry1 );
break;
default:
postfix[p++] = Entry1;
break;
}
}
}
//while stack is not empty

while ( !oStackOperation.IsStackEmpty() )
postfix[p++] = oStackOperation.Pop();
postfix[p] = '\0';
cout << "\nThe postfix expression is: " << postfix << endl;
}
int PrecedenceSymbol ( char symbol )
{
switch ( symbol )
{
// Precedence of / is 4
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:

);

return ( -1 );
}
}
};
main()
{
char choice = 'y';
InfixToPostfix oInfixToPostfix;
while ( choice == 'y' )
{
oInfixToPostfix.ReadInfixExpr();
oInfixToPostfix.ConvertToPostfix();
cout << "\n\nDo you want to continue ? (y/n): "; cin
>> choice;
}
return 0;
}
Output

d)
Evaluatio
n of
Postfix
Expressio
n
#include
<iostream>
#include <stdlib.h>
#include <math.h>

using namespace std;


const int MAX = 50 ;
class PostfixExpressionEvaluation
{
private :
int mStack[MAX] ;
int mTopofstack, mReturnvalue ;
char *ptemp ;
public :
PostfixExpressionEvaluation( ) ;
void SetExpression(char *pstr ) ;
void Push ( int item ) ;
int Pop( ) ;
void Evaluate( ) ;
void Show( ) ;
};
PostfixExpressionEvaluation :: PostfixExpressionEvaluation( )
{
mTopofstack = -1 ;
}
void PostfixExpressionEvaluation :: SetExpression ( char *pstr )
{
ptemp = pstr ;
}
void PostfixExpressionEvaluation :: Push ( int item )
{
if ( mTopofstack ==MAX - 1 )

cout << endl << "Stack is full" ;


else
{
mTopofstack++ ;
mStack[mTopofstack] = item ;
}
}
int PostfixExpressionEvaluation ::Pop( )
{
if ( mTopofstack == -1 )
{
cout << endl << "Stack is empty" ;
return NULL ;
}
int data = mStack[mTopofstack];
mTopofstack-- ;
return data ;
}
void PostfixExpressionEvaluation :: Evaluate( )
{
int value1, value2, result ;
while ( *ptemp )
{
if ( *ptemp == ' ' || *ptemp == '\t' )
{
ptemp++ ;
continue ;

}
if ( isdigit ( *ptemp ) )
{
mReturnvalue = *ptemp - '0' ;

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

}
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

e) Circular Queue Application of queue


#include<iostream>
#include<stdlib.h>
using namespace std;
const int MAX = 5;
class CircularQueue
{
int mQueue[MAX], mFront, mRear;
public :
CircularQueue()
{
mFront = mRear = -1;
}
void Insertion ( int ); int
Deletion();

void Display();
};
void CircularQueue :: Insertion ( int val )
{
if ( ( mFront == 0 && mRear == MAX - 1 ) || ( mRear + 1 == mFront ) )
cout << " Circular Queue is Full";
else
{
if ( mRear == MAX - 1 )
mRear = 0;
else
mRear++;
mQueue[mRear] = val;
}
if ( mFront == -1 )
mFront = 0;
}
int CircularQueue :: Deletion()
{
int return_value;
if ( mFront == -1 )
cout << "Circular Queue is Empty";
else
{
return_value = mQueue[mFront];
if ( mFront == mRear )
mFront = mRear = -1;

else
{
if ( mFront == MAX - 1 )
mFront = 0;
else
mFront++;
}
}
return return_value;
}
void CircularQueue :: Display()
{
int i;
if ( mFront == -1 )
cout << "Circular Queue is Empty";
else
{
if ( mRear < mFront )
{
for ( i = mFront;i <= MAX - 1;i++ )
cout << mQueue[i] << " ";

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


cout << mQueue[i] << " ";
}
else
{
for ( i = mFront;i <= mRear;i++ )
cout << mQueue[i] << "

";

cout << endl;


}
}
}
main()
{
CircularQueue oCircularQueue;
int get_choice, get_element;
char option;
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;

case 3 :
oCircularQueue.Display();
break;
}
cout << "Do you want to continue<Y/N> ?";
cin >> option;
}
while ( option == 'Y' || option == 'y' );
}
Output

12) Implementation of Binary search tree


#include<iostream>
#include <process.h>

#include<stdlib.h>
#include <malloc.h>
using namespace std;
struct Node
{
int Element;
Node *pLeft;
Node *pRight;
};
//pNode is a node pointer
typedef struct Node *pNode;
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 & );

};
void BinarySearchTree::Insertion ( int new_element, pNode& oRoot )
{
if ( oRoot == NULL )
{
oRoot = new Node; oRoot>Element = new_element;
oRoot->pLeft = NULL; oRoot>pRight = NULL;
}
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 !";
}
}
void BinarySearchTree:: Deletion ( int new_element, pNode& oRoot )
{
pNode oNode;
if ( oRoot == NULL )
cout << "Element not found ";
else

if ( new_element < oRoot->Element )


Deletion ( new_element, oRoot->pLeft );
else
if ( new_element > oRoot->Element )
Deletion ( new_element, oRoot->pRight );
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 );

else
oRoot->Element = DeleteMinElement ( oRoot->pRight );
}
int BinarySearchTree::DeleteMinElement ( pNode& oRoot )
{
int result;;
if ( oRoot->pLeft == NULL )
{
result = oRoot->Element;
oRoot = oRoot->pRight;
return result;
}
else
result = DeleteMinElement ( oRoot->pLeft );
return result;
}
void BinarySearchTree::MakeEmpty ( pNode& oRoot )
{
pNode oNode;
if ( oRoot != NULL )
{
MakeEmpty ( oRoot->pLeft );
MakeEmpty ( oRoot->pRight
); oNode = oRoot;
free ( oNode );

oRoot = NULL;
}
}
pNode BinarySearchTree::FindMinElement ( pNode oRoot )
{
if ( oRoot == NULL )
{
cout << "Tree is empty !";
return oRoot;
}
else
{
while ( oRoot->pLeft != NULL )
oRoot = oRoot->pLeft;
return oRoot;
}
}
pNode BinarySearchTree::FindMaxElement ( pNode oRoot )
{
if ( oRoot == NULL )
{
cout << "Tree is empty !";
return oRoot;
}
else
{

while ( oRoot->pRight != NULL )


oRoot = oRoot->pRight;
return oRoot;
}
}
void BinarySearchTree::Find ( int x, pNode& oRoot )
{
if ( oRoot == NULL )
cout << "Element not found !";
else
{
if ( x < oRoot->Element )
Find ( x, oRoot->pLeft );
else
if ( x > oRoot->Element )
Find ( x, oRoot->pRight );
else
cout << "Element Found !";
}
}
void BinarySearchTree::Preorder ( pNode oRoot )
{
if ( oRoot != NULL )
{
cout << oRoot->Element << "-->";
Preorder ( oRoot->pLeft );

Preorder ( oRoot->pRight );
}
}
void BinarySearchTree::Inorder ( pNode oRoot )
{
if ( oRoot != NULL )
{
Inorder ( oRoot->pLeft );
cout << oRoot->Element << "-->";
Inorder ( oRoot->pRight );
}
}
void BinarySearchTree::Postorder ( pNode oRoot )
{
if ( oRoot != NULL )
{
Postorder ( oRoot->pLeft );
Postorder ( oRoot->pRight ); cout
<< oRoot->Element << "-->";
}
}
void BinarySearchTree::FindLeftChild ( int left_child, pNode& oRoot )
{
if ( oRoot == NULL )
cout << "The node does not exists ";
else
if ( left_child < oRoot->Element )

FindLeftChild ( left_child, oRoot->pLeft );


else
if ( left_child > oRoot->Element )
FindLeftChild ( left_child, oRoot->pRight ); else
if ( left_child == oRoot->Element )
{
if ( oRoot->pLeft != NULL )
cout << "Left child of " << left_child << "is " << oRoot>pLeft->Element;
else
cout << "No Left child !";
}
}
void BinarySearchTree::FindRightChild ( int right_child, pNode& oRoot )
{
if ( oRoot == NULL )
cout << "The node does not exists ";
else
if ( right_child < oRoot->Element )
FindRightChild ( right_child, oRoot->pLeft ); else
if ( right_child > oRoot->Element )
FindRightChild ( right_child, oRoot->pRight );
else
if ( right_child == oRoot->Element )
{
if ( oRoot->pRight != NULL )

cout << "Right child of " << right_child << "is " << oRoot>pRight->Element;
else
cout << "No Right Child !";
}
}
int main()
{
int choice, element, left_child , right_child;
BinarySearchTree oBst;
char c = 'y';
pNode root, min, max;
root = NULL;
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 ";

cout << "Enter the new element to get inserted : "; cin
>> element;
oBst.Insertion ( element, root ); cout
<< "Inorder traversal is : ";
oBst.Inorder ( root );
break;
case 2:
cout << " 2.Deletion \n";
cout << "Enter the element to get deleted : "; cin
>> element;
oBst.Deletion ( element, root );
oBst.Inorder ( root );
break;

case 3:
cout << " 3.Find \n";
cout << "Enter the element to be searched : ";
cin >> element;
oBst.Find ( element, root );
break;
case 4:
cout << " 4.Findmax \n";
if ( root == NULL )
cout << " Tree is empty";
else
{
max = oBst.FindMaxElement ( root );

cout << "Largest element is : " << max->Element << endl;


}
break;
case 5:
cout << " 5.Findmin \n";
if ( root == NULL )
cout << " Tree is empty";
else
{
min = oBst.FindMinElement ( root );
cout << "Smallest element is : " << min->Element << endl;
}
break;
case 6:
cout << " 6.Preorder \n";
if ( root == NULL )
cout << " Tree is empty";
else
{
cout << "Preorder traversal (Recursive) is : ";
oBst.Preorder ( root );
}
break;

case 7:
cout << " 7.Inorder\n ";
if ( root == NULL )
cout << " Tree is empty";
else
{
cout << " Inorder traversal (Recursive) is : ";
oBst.Inorder ( root );
}
break;
case 8:
cout << " 8.Postorder \n";
if ( root == NULL )
cout << "Tree is empty";
else
{
cout << "Postorder traversal (Recursive) is : ";
oBst.Postorder ( root );
}
break;
case 9:
cout << " 9.Finding the left Child \n";

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:
cout << " 10.Finding the Right Child\n";
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 );
}
cout << "\n Continue (y/n) ? ";

cin >> c;
}
while ( c == 'y' || c == 'Y' );
return 0;
}
Output

13. Implementation of Tree Traversal


#include<iostream>
#include <process.h>
#include<stdlib.h>
#include <malloc.h>
using namespace std;
struct Node
{

int Element;
Node *pLeft;
Node *pRight;
};
//pNode is a node pointer
typedef struct Node *pNode;
class BinarySearchTree
{
public:
void Insertion ( int, pNode & );
void MakeEmpty ( pNode & ); void
Preorder ( pNode );
void Inorder ( pNode );
void Postorder ( pNode );
};
void BinarySearchTree::Insertion ( int new_element, pNode& oRoot )
{
if ( oRoot == NULL )
{
oRoot = new Node; oRoot>Element = new_element;
oRoot->pLeft = NULL; oRoot>pRight = NULL;
}
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 !";
}
}
void BinarySearchTree::Preorder ( pNode root )
{
if ( root != NULL )
{
cout << root->Element << "-->";
Preorder ( root->pLeft );
Preorder ( root->pRight );
}
}
void BinarySearchTree::Inorder ( pNode root )
{
if ( root != NULL )
{
Inorder ( root->pLeft );
cout << root->Element << "-->";
Inorder ( root->pRight );
}
}
void BinarySearchTree::Postorder ( pNode root )
{

if ( root != NULL )
{
Postorder ( root->pLeft );
Postorder ( root->pRight ); cout
<< root->Element << "-->";
}
}
int main()
{
int choice, element, left_child , right_child;
BinarySearchTree oBst;
char c = 'y';
pNode root, min, max;
root = NULL;
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 ";

cout << "Enter the new element to get inserted : "; cin
>> element;
oBst.Insertion ( element, root ); cout
<< "Inorder traversal is : ";
oBst.Inorder ( root );
break;
case 2:
cout << " 2.Preorder \n";
if ( root == NULL )
cout << " Tree is empty";
else
{
cout << "Preorder traversal (Recursive) is : ";
oBst.Preorder ( root );
}
break;

case 3:
cout << " 3.Inorder\n ";
if ( root == NULL )
cout << " Tree is empty";
else
{
cout << " Inorder traversal (Recursive) is : ";
oBst.Inorder ( root );
}

break;
case 4:
cout << " 4.Postorder \n";
if ( root == NULL )
cout << "Tree is empty";
else
{
cout << "Postorder traversal (Recursive) is : ";
oBst.Postorder ( root );
}
break;
case 0:
exit ( 0 );
}
cout << "\n Continue (y/n) ? ";
cin >> c;
}
while ( c == 'y' || c == 'Y' );
return 0;
}
Output:

14. Minimum Spanning Tree


a) Prim's Algorithm
#include<iostream>
#include<stdlib.h>
using namespace std;
class PrimsAlgorithm
{
private:
// No of nodes
int mNumberOfNodes;
// Edges in the graph
int mGraphEdge[250][4];

/ No of edges in the graph int


mNumberOfEdges;
/ Edges in the tree
int mTreeEdge[250][4];
// No of edges in the tree int
mNumberOfTreeEdges;

//Partition the graph in to two sets //


Set 1
int mSet1Array[50], mSet1;
// Set 2
int mSet2Array[50], mSet2;
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";
for ( int i = 1;i <= mNumberOfNodes;i++ )
{
for ( int j = i + 1;j <= mNumberOfNodes;j++ )
{

cout << " < " << i << " , " << j << " > ::";
int w;
cin >> w;
if ( w != 0 )
{
mNumberOfEdges++;
mGraphEdge[mNumberOfEdges][1] =
i; mGraphEdge[mNumberOfEdges][2]
= j; mGraphEdge[mNumberOfEdges]
[3] = w;

}
}
}
// print the graph edges
cout << "\n\nThe edges in the given graph are::\n";
for ( int i = 1;i <= mNumberOfEdges;i++ )
{
cout << " < " << mGraphEdge[i][1] << " , " << mGraphEdge[i][2] << " >
::" << mGraphEdge[i][3] << endl;
}
}
int PrimsAlgorithm::Findset ( int x )
{
for ( int i = 1;i <= mSet1;i++ )
if ( x == mSet1Array[i] )
return 1;
for ( int i = 1;i <= mSet2;i++ )
if ( x == mSet2Array[i] )

return 2;
return -1;
}
void PrimsAlgorithm::Algorithm()
{
mNumberOfTreeEdges =
0; mSet1 = 1;
// Fixing Source Node
mSet1Array[1] = 1;

mSet2 = mNumberOfNodes 1; int i;


for ( i = 1;i <= mNumberOfNodes - 1;i++ )
// Finding reamining nodes
mSet2Array[i] = i + 1;

cout << "\n*****The algorithm starts*****\n\n";


while ( mNumberOfEdges != 0 && mNumberOfTreeEdges != mNumberOfNodes 1)
{
// Find the least cost edge int
min = 9999;
int p;
int edge1, edge2, edge3;
for ( i = 1;i <= mNumberOfEdges;i++ )
{
bool flag1 = false, flag2 = false;
// if u and v are in different sets
if ( Findset ( mGraphEdge[i][1] ) != Findset ( mGraphEdge[i][2] ) )

{
if ( min > mGraphEdge[i][3] )
{
min = mGraphEdge[i][3];
edge1 = mGraphEdge[i][1];
edge2 = mGraphEdge[i][2];
edge3 = mGraphEdge[i][3];
p = i;

}
}
}
// Break if there is no such edge
cout << "The edge included in the tree is ::";
cout << " < " << edge1 << " , " << edge2 << " > " << endl;
// Delete the edge from graph edges
for ( int l = p;l < mNumberOfEdges;l++ )
{
mGraphEdge[l][1]
[1];

mGraphEdge[l+1]

mGraphEdge[l][2]

mGraphEdge[l+1][2];

mGraphEdge[l][3]

= mGraphEdge[l+1][3];

}
mNumberOfEdges--;
// Add the edge to the tree
mNumberOfTreeEdges++;
mTreeEdge[mNumberOfTreeEdges][1] =
edge1; mTreeEdge[mNumberOfTreeEdges]
[2] = edge2;
mTreeEdge[mNumberOfTreeEdges][3] =

edge3;

// Alter the set partitions


mSet1+
+; int
m;
if ( Findset ( edge2 ) == 2 )
{
mSet1Array[mSet1] =
edge2; m = edge2;
}
else
if ( Findset ( edge1 ) == 2 )
{
mSet1Array[mSet1] =
edge1; m = edge1;
}
int x;
for ( x = 1;mSet2Array[x] != m;x++ );
for ( ;x < mSet2;x++ )
mSet2Array[x] = mSet2Array[x+1];
mSet2--;
// Print the sets int
k;
cout << "NOW\nSet1 :: ";
for ( k = 1;k <= mSet1;k++ )
cout << mSet1Array[k] << ' ';

cout << endl;


cout << "Set2 :: ";
for ( k = 1;k <= mSet2;k++ )
cout << mSet2Array[k] << ' ';

cout << endl;


cout << "The graph edges are ::\n";
for ( i = 1;i <= mNumberOfEdges;i++ )
cout << " < " << mGraphEdge[i][1] << " , " << mGraphEdge[i][2] << "
> ::" << mGraphEdge[i][3] << endl;
cout << endl << endl;
}
}
void PrimsAlgorithm::Output()
{
cout << "\nThe selected edges are ::\n";
for ( int i = 1;i <= mNumberOfTreeEdges;i++ )
{
cout << " < " << mTreeEdge[i][1] << " , " << mTreeEdge[i][2] << " > ::"
<< mTreeEdge[i][3] << endl;
}
}
int main()
{

PrimsAlgorithm oprims;
oprims.Input();
oprims.Algorithm();
oprims.Output();
return 0;
}
Output

b) Kruskal Algorithm
#include<iostream>
#include<conio.h>
using namespace std;
int gParent [10];
class KruskalAlgorithm
{
int mNode1, mNode2, mUnvisited, mVisited, i, j, mNoOfNodes, mNoOfEdges;
int mMinimumValue, mMinimumCost, mCost[10][10];
public:
KruskalAlgorithm()
{
mNoOfEdges = 1;
mMinimumCost = 0;
}

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";
for ( i = 1;i <= mNoOfNodes;i++ )
for ( j = 1;j <= mNoOfNodes;j++ )
{
cin >> mCost[i][j];
if ( mCost[i][j] == 0 )
mCost[i][j] = 999;
}
mKruskal ( mCost, mNoOfNodes );
}
void KruskalAlgorithm::mKruskal ( int cost[][10], int n )
{
cout << "the minimum cost edges are\n";
while ( mNoOfEdges < n )
{
mMinimumValue = 999;
for ( i = 1;i <= n;i++ )
for ( j = 1;j <= n;j++ )
if ( cost[i][j] < mMinimumValue )

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

}
cost[mNode1][mNode2] = cost[mNode2][mNode1] = 999;
}
cout << "\nminimum cost=" << mMinimumCost;
}
main()
{
KruskalAlgorithm oKruskalAlgorithm;
oKruskalAlgorithm.ReadGraph();
}

Output

15. Shortest Path Algorithm


a) Dijkstra's Algorithm
#include<iostream>
#define INFINITY 999
using namespace std;
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();

void Initialize();
int
GetClosestUnmarkedNode();
void CalculateDistance(); void
Output();
void PrintShortestPath ( int );
};
/* Read number of vertices, source vertex and Adjacency Matrix*/
void DijkstraAlgorithm::ReadVertex()
{
cout << "Enter the number of vertices of the graph(should be > 0)\n"; cin
>> mNumOfVertices;
while ( mNumOfVertices <= 0 )
{
cout << "Enter the number of vertices of the graph(should be > 0)\n"; cin
>> mNumOfVertices;
}
cout << "Enter the adjacency matrix for the graph\n";
cout << "To enter infinity enter " << INFINITY << endl;
for ( int i = 0;i < mNumOfVertices;i++ )
{
cout << "Enter the (+ve)weights for the row " << i << endl;
for ( int j = 0;j < mNumOfVertices;j++ )
{
cin >> mAdjMatrix[i][j];
while ( mAdjMatrix[i][j] < 0 )
{

cout << "Weights should be +ve. Enter the weight again\n";


cin >> mAdjMatrix[i][j];
}
}
}
cout << "Enter the source vertex\n";
cin >> mSourceVertex;
while ( ( mSourceVertex < 0 ) && ( mSourceVertex > mNumOfVertices - 1 ) )
{
cout << "Source vertex should be between 0 and" << mNumOfVertices - 1
<< endl;
cout << "Enter the source vertex again\n";
cin >> mSourceVertex;
}
}
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()
{

int min_distance = INFINITY;


int closest_unmarked_node;
for ( int i = 0;i < mNumOfVertices;i++ )
{
if ( ( !mMark[i] ) && ( min_distance >= mDistance[i] ) )
{
min_distance = mDistance[i];
closest_unmarked_node = i;

}
}
return closest_unmarked_node;
}
void DijkstraAlgorithm::CalculateDistance()
{
Initialize();
int min_distance = INFINITY;
int closest_unmarked_node;
int count = 0;
while ( count < mNumOfVertices )
{
closest_unmarked_node =
GetClosestUnmarkedNode();
mMark[closest_unmarked_node] = true;
for ( int i = 0;i < mNumOfVertices;i++ )
{
if ( ( !mMark[i] ) && ( mAdjMatrix[closest_unmarked_node][i] > 0 )
)
{

if ( mDistance[i] > mDistance[closest_unmarked_node] +


mAdjMatrix[closest_unmarked_node][i] )
{
mDistance[i] = mDistance[closest_unmarked_node]
+ mAdjMatrix[closest_unmarked_node][i];
mPredecessor[i] = closest_unmarked_node;
}
}
}
count++;
}
}
void DijkstraAlgorithm::PrintShortestPath ( int node )
{
if ( node == mSourceVertex )
cout << ( char ) ( node + 97 ) << "..";
else
if ( mPredecessor[node] == -1 )
cout << "No path from <<source<<to " << ( char ) ( node + 97 ) <<
endl;
else
{
PrintShortestPath ( mPredecessor[node] );
cout << ( char ) ( node + 97 ) << "..";
}
}
void DijkstraAlgorithm::Output()
{
for ( int i = 0;i < mNumOfVertices;i++ )
{

if ( i == mSourceVertex )
cout << ( char ) ( mSourceVertex + 97 ) << ".." << mSourceVertex;
else
PrintShortestPath ( i );
cout << "->" << mDistance[i] << endl;
}
}
int main()
{
DijkstraAlgorithm oDijkstraAlgorithm;
oDijkstraAlgorithm.ReadVertex();
oDijkstraAlgorithm.CalculateDistance();
oDijkstraAlgorithm.Output();
return 0;
}
Output

b) Bellman Ford Algorithm


#include<iostream>
#include<stdlib.h>
#define MAX 20

#define INFINITY 9999


using namespace std;
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";
for ( int i = 1;i <= mNoOfNodes;i++ )
for ( int j = 1;j <= mNoOfNodes;j++ )
cin >> mAdjacentMatrix[i][j];
cout << "Enter the start vertex ::";

cin >> mStartVertex;


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

}
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 << "\n\nThere is no negative weight cycle and\n";
cout << "****** The final paths and the distacnes are ******\n\n";
for ( int i = 1;i <= mNoOfNodes;i++ )
{
cout << "path for node " << i << " is ::\n"; int
arr[MAX], k = 1;
int j = i;
while ( mPredecessor[j] != 0 )
{
arr[k] = mPredecessor[j];
k++;

j = mPredecessor[j];
}
for ( -k;k > 0;k-- ) cout <<
arr[k] << "->";

cout << i << endl;


cout << "distance is " << mDistance[i] << endl << endl << endl;
}
}
void BellFordAlgorithm::Algorithm()
{
ReadGraph();
Initialize();
Update();
Check();
}
main()
{
BellFordAlgorithm oBellFordAlgorithm;
oBellFordAlgorithm.Algorithm();
}
Output

c) Floyds Warshall Algorithm


#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
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();
};

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 :";
for ( i = 1;i <= mNoOfNodes;i++ )
{
for ( j = 1;j <= mNoOfNodes;j++ )
{
cin >> mAdjacencyMatrix[i][j];
mPathMatrix[i][j] = 0;

}
}
cout << "Enter The cost matrix is :";
for ( i = 1;i <= mNoOfNodes;i++ )
{
for ( j = 1;j <= mNoOfNodes;j++ )
{
// cout<<"a["<<i<<","<<j<<"] = ";
cin >> mGraphCost[i][j];
}
}
for ( i = 1;i <= mNoOfNodes;i++ )
{
for ( j = 1;j <= mNoOfNodes;j++ )
{

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

";

}
cout << endl;
}
}
void FloydsWarshallAlgorithm::PathMatrix()
{
int i, j,

k;

for ( k =

1;k <= mNoOfNodes;k++ )

{
for ( i= 1;i <= mNoOfNodes;i++ )
{
for( j = 1;j <= mNoOfNodes;j++ )
{
mPathMatrix[i][j] = mPathMatrix[i][j] || mPathMatrix[i][k] &&
mPathMatrix[k][j];
}

}
}
}
void FloydsWarshallAlgorithm::Algorithm()
{
int i, j, k;
for ( i = 1;i <= mNoOfNodes;i++ )
{
for ( j = 1;j <= mNoOfNodes;j++ )
{
mPathMatrix[i][j] = mGraphCost[i][j];
}
}
for ( k = 1;k <= mNoOfNodes;k++ )
{
for ( i = 1;i <= mNoOfNodes;i++ )
{
for ( j = 1;j <= mNoOfNodes;j++ )
{
if ( mPathMatrix[i][j] < mPathMatrix[i][k] + mPathMatrix[k][j]
)
{
mPathMatrix[i][j] = mPathMatrix[i][j];
}
else
{

mPathMatrix[i][j] = mPathMatrix[i][k] + mPathMatrix[k][j];


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