Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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);
}
// 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:
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:
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
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:
//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:
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
{
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
return input;
}
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;
}
int main()
{
ComplexOperations oNumberOne, oNumberTwo, oNumberThree;
cout
cin
cout
cin
cout
<<
>> oNumberOne;
<< "complex number 2: ";
>> oNumberTwo;
<< "complex numbers are:";
oNumberThree =
oNumberOne
* oNumberTwo;
return 0;
<< oNumberThree;
}
Output
{
// Returns greatest number
retur number_one <
n
number_two
}
int main ()
? number_two : number_one;
{
/
int_number_one, int_number_two;
/
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;
}
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:
}
// Catch the "Positive Number Required" exception.
catch ( const char* Message )
{
cout << "Error: " << Message;
}
Output:
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:
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);
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;
for ( i =
vec3.push_back ( i );
// print all elements separated by a space
for ( i =
!= 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
<<
< vec2 )
"vec1 vector less than vec2 vector." << endl;
> vec1 )
cout << "vec2 vector greater than vec1 vector." << endl;
else
cout
<<
>= vec1 )
"vec2 vector greater or equal than vec1 vector." << endl;
"vec2 vector is not greater or equal than vec1 vector." << endl;
cout << "The number of elements in vector_two = " << vector_two.size() <<
endl;
cout << endl;
return 0;
}
Output
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;
max_size(): "
sentence.back() = "!";
/
endl;
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;
);
c) Iterator
Iterator - a list container
#include <iostream>
#include <list>
using namespace
std;
int main()
{
Output:
Output
#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
}
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
Output:
}
//Close the text file opened in read mode
oFileinput.close();
return 0;
}
Output:
while ( !oFileinput.eof() )
{
/
oFileinput.get ( char_text );
/
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:
#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:
{
// 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
oFileinput.open ( "out.txt" );
/
ofstream oFileoutput;
/
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;
else
{
cout << "Do you want to continue Y/N:";
cin >> Continue;
}
}
while ( Continue != 'N' );
BE_StudFile_Output.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();
oFileoutput.close();
// open a file in read mode.
ifstream oFileinput;
oFileinput.open ( "personalfile.dat" );
cout << "Reading from the file" << endl;
oFileinput >> Personal_data;
again read the data from the file and display it.
return 0;
}
Output
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
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;
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:
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>
}
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
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] << " ";
";
case 3 :
oCircularQueue.Display();
break;
}
cout << "Do you want to continue<Y/N> ?";
cin >> option;
}
while ( option == 'Y' || option == 'y' );
}
Output
#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
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
{
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 )
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 );
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
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 )
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:
<
"*************************************************\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;
{
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;
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
<<
{
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
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 )
{
}
}
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 ( 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
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 ::";
}
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] << "->";
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 =
{
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
{