Professional Documents
Culture Documents
LAB MANUAL
NAME :
REGNO :
YEAR / SEM :
DEPT :
PAGE
S.NO EXPERIMENT NAME SIGNATURE
NO.
CONSTRUCTORS & DESTRUCTORS, COPY
1
CONSTRUCTOR
FRIEND FUNCTION & FRIEND CLASS.
2
3 INHERITANCE
5 VIRTUAL FUNCTIONS
Aim
Algorithm
1. Start
2. Declare class distance containing data members inch and feet.
3. Define default constructor that initializes data members to 0.
4. Define parameterized constructor that initializes data members with values provided.
5. Define display function to print value of data members
6. Create distance objects to invoke the constructors.
7. Call display function for each distance object.
8. Stop
Program
// 1a - Constructor types
#include <iostream.h>
class distance
{
int feet; int inch;
public:
distance() // Default constructor
{ feet = 0; inch = 0;
}
distance (int n, int d = 0) //Parameterized constructor
{ feet = n; inch = d;
}
void print()
Output
0.0ft
4.0ft
22.7ft
Result
Algorithm
1. Start
2. Declare class complex with data members real and imag
3. Define parameterized constructor that initializes data members with given values
4. Define copy constructor that uses an object reference to initialize data members of
another object
5. Define display function to print data members
6. Create complex objects that invoke copy constructor in various ways.
7. Call display function for each distance object.
8. Stop
Program
// 1b Copy Constructor
#include <iostream.h>
class complex
{ real = r; imag = i;
void display()
{ cout << real << " + " << imag << "i \n"; }
};
int main()
Output
2 + 3i
6 + -2i
Result
To allocate memory for objects dynamically and release memory using destructor.
Algorithm
1. Start
2. Declare class mystring with data member str and len
3. Define dynamic constructor using new operator
4. Define display function to print string contents
5. Define destructor that releases memory using delete operator
6. Create objects using constructor and invoke destructor when they go out of scope
7. Stop
Program
// 1c Destructor
#include <iostream.h>
#include <string.h>
class mystring
public:
mystring (char *s) // Dynamic constructor
{
~mystring() // Destructor
{ delete[] str;
};
int main()
Output
PCET
Memory released
Result
Algorithm
1. Start
2. Declare class sample with data members
3. Define a non-member function mean that returns aggregate of data members
4. Declare function mean as friend to class sample
5. Provide value for data members
6. Call function mean
7. Stop
Program
// 2a friend function
#include <iostream.h>
class sample
{ int a; int b;
{ a = 25; b = 40;
}
};
float mean(sample s)
int main()
{ sample X; X.setvalue();
Output
Result
Thus data members of a class were accessed by a non-member function using friend
keyword.
Algorithm
1. Start
2. Declare class rectangle with length and breadth as data members
3. Declare class square with side as data member
4. Declare class rectangle as friend to class square
5. Define function convert in rectangle class that takes square object as argument
6. Create objects for both classes
7. Call function convert to demonstrate friend class.
8. Stop
Program
// 2b Friend class
#include <iostream.h>
class square;
class rectangle
};
public:
square (int a)
{ side = a;
};
void rectangle::convert(square a)
int main()
return 0;
Output
Rectangle area : 16
Result
Thus a class was declared as a friend to another class and its usage demonstrated.
Algorithm
1. Start
2. Declare class rectangle with protected members length and breadth
3. Define function rectdim to read values
4. Derive class box from rectangle in public mode with data member depth.
5. Define function getdata for box class that calls rectdim function
6. Create object for box class 7. Display volume of the box.
8. Stop
Program
#include <iostream.h>
class rectangle
};
{ rectdim();
void display()
int main()
Output
Enter depth : 6
Result
Thus single inheritance is demonstrated by having box class derived from rectangle.
Algorithm
1. Start
2. Declare class person with protected members name, age and gender.
3. Define member function getperson and dispperson for person class.
4. Derive class student from person in public mode with members regno and course
5. Define member function getstudent and dispstudent for student class 6. Derive class
staff from person in public mode with members qualfn and salary
7. Define member function getstaff and dispstaff for staff class.
8. Create objects for both student and staff class
9. Call functions belonging to person class as well as its own class for both objects.
10. Stop
Program
class person
void dispperson()
{ cout << "Name : " << name << "\n"; cout << "Gender : " <<
gender << "\n"; cout << "Age : " << age << "\n";
} };
{ protected:
} void dispstudent()
{ cout << "\n" << "Register No. : " << regno << "\n"
{ protected:
cout << " Enter basic pay : "; cin >> salary;
void dispstaff()
{ cout << "Degree : " << qualfn << "\n"; cout << "Salary : " <<
salary << "\n";
} };
int main()
Output
General Details
Enter age : 20
Enter gender : M
Student Details
Gender : M
Age : 20
Course : B.E(CSE)
General Details
Enter age : 35
Enter gender : M
Staff Details
Name : Suresh
Gender : M
Age : 35
Degree : M.Tech
Salary : 23456
Result
Thus student and staff class were derived from person class in a hierarchical manner.
Algorithm
1. Start
2. Declare class hslc with protected members math, phy and chem.
3. Define function getmarks to provide inputs for hslc class
4. Declare class entrance with protected member score
5. Define function getscore to provide inputs for entrance class.
6. Derive class result from classes hslc and entrance in public mode 7. Define
function process that calls function getmarks and getscore
8. Define function display to print cut-off mark.
9. Create object for result class
10. Call process and display function
11. Stop
Program
// 3c multiple inheritance
#include <iostream.h>
class hslc {
protected: int math;
int phy; int chem;
class entrance
} };
{ getmarks();
getscore();
cutoff=float(math/2+phy/4+chem/4+score);
void display()
} };
int main()
Cut-off : 198
Result
Thus result class exhibits multiple inheritance by inheriting members from hslc and
entrance class.
Algorithm
1. Start
2. Declare class vertebrate with function eat
3. Derive class mammal from vertebrate publicly with function suckle
4. Derive class primate from mammal publicly with function peel
5. Derive class human from primate publicly with function think
6. Create object for human class
7. Call derived functions eat, suckle and peel and its own function think
8. Stop
Program
// 3d multilevel inheritance
#include <iostream.h>
class vertebrate
} };
} };
int main()
Output
Result
Thus evolution of mankind from vertebrates is demonstrated using multilevel inheritance.
Algorithm
1. Start
2. Declare class hslc with data members name and percent.
3. Define function gethslc and disphslc functions for hslc class
4. Derive class ug from hslc publicly with members course and cgpa
5. Define function getug and dispug for ug class
6. Declare class gate with data member score
7. Derive class pg from classes ug and gate publicly with member rank.
8. Define function getpg and disppg for pg class
9. Create object for pg class
10. Call all implementor functions
11. Call all accessor functions
12. Stop
Program
// 3e hybrid inheritance
#include <iostream.h>
class hslc {
protected:
{ cout << "Enter name and hslc percentage : "; cin >> name >> percent;
void disphslc()
{ cout << "\n" << "Name : " << name << "\n"; cout << "Percentage : " <<
percent << "% \n"; }
};
{ cout << "Enter course and cgpa : "; cin >> course >>
cgpa;
} void dispug()
{ cout << "Course " << course << "\n"; cout << "CGPA : "
<< cgpa << "\n";
} };
void dispgate()
void disppg()
} };
int main()
{ pg p1; p1.gethslc();
p1.getug();
p1.getgate();
p1.getpg();
p1.disphslc(); p1.dispug();
p1.dispgate(); p1.disppg();
Output
Enter rank : 6
Percentage : 68%
Course B.E(CSE)
CGPA : 7.34
Gate score : 44
Rank : 6
Result
Algorithm
1. Start
2. Declare prototypes for function volume to compute volume of cube, box and
cylinder.
3. Define volume functions that varies on argument and implementation.
4. Call volume function with corresponding arguments
5. Stop
Program
// 4a function overloading
#include <iostream.h>
const float pi = 3.14;
int volume(int); // cube volume
int volume(int, int, int); // box volume float volume(int, int); // cylinder volume
int main() {
return 0;
int volume(int a)
{ return (l * b * h);
Output
Cube volume : 125
Result
Thus volume of cube, box and cylinder is accomplished using different version of volume
function.
Algorithm
1. Start
2. Declare class vehicle with protected members capacity, fuel, feature and virtual
function display
3. Derive class bicycle, autorickshaw and lorry from vehicle publicly.
4. Define default constructor for derived classes to initialize derived data members.
5. Redefine display function to print details for the corresponding vehicle
6. Create a vehicle class pointer and assign bicycle / autorickshaw / lorry object
7. Call display function to demonstrate runtime polymorphism
8. Stop
Program
// 5a virtual functions
#include <iostream.h>
#include <string.h>
class vehicle
{ protected:
};
{ public: bicycle()
void display()
cout << "Capacity : " << capacity << "\n"; cout << "Fuel : " <<
fuel << "\n"; cout << "Features : " << feature << "\n";
} };
{ public: autorikshaw()
{ capacity = 3;
void display()
{ cout << "\n Autorickshaw \n"; cout << "Capacity : " << capacity <<
"\n"; cout << "Fuel : " << fuel << "\n"; cout << "Features : " <<
feature << "\n";
};
{ public: lorry()
void display()
cout << "Capacity : " << capacity << "\n"; cout << "Fuel : " <<
fuel << "\n"; cout << "Features : " << feature << "\n";
} };
int main()
Capacity : 2
Fuel : Air
Autorickshaw
Capacity : 3
Fuel : Petrol/Diesel/LPG
Lorry
Capacity : 2
Fuel : Diesel
Result
Thus dynamic or late binding is implemented by virtual function using hierarchical
inheritance of vehicle class.
Aim
To overload unary operator using member function.
Algorithm
1. Start
2. Declare class space with data members x, y and z
3. Define parameterized constructor for space class
4. Define display function to print data members
5. Overload unary minus () using operator member function
6. Create a space object
7. Invoke unary minus on space object 8. Call display member function.
9. Stop
Program
// 6a unary operator using member function
#include <iostream.h>
class space
{ x = a; y = b; z
= c; }
void display()
{ cout << x << " " << y << " " << z;
{ x = -x; y = -y; z
= -z;
};
int main()
S.display();
S.display(); return 0;
Output
Original 3D coordinates : 1 2 -3
Negated 3D coordinates : -1 -2 3
Result
Thus unary minus operator was overloaded using operator member function.
Aim
To overload unary operator ++ on fraction number using friend function.
Algorithm
1. Start
2. Declare class fraction with data members num and den
3. Define parameterized constructor for fraction class
4. Define display function to print data members
5. Declare operator function to overload ++ as friend to class fraction
6. Overload increment operator (++) as a non-member function
7. Create a fraction object
8. Invoke increment operator on fraction object
9. Call display member function.
10. Stop
Program
// 6b unary operator using friend function
#include <iostream.h>
class fraction
{ num = n; den =
d;
void display()
};
int main()
f1.display();
Output
Result
Thus pre increment operator ++ was overloaded as a friend function.
Aim
To overload operator + to perform addition of two distance objects.
Algorithm
1. Start
2. Declare class distance with data members inch and feet
3. Define default and parameterized constructor for distance class
4. Define display function to print data members
5. Overload operator + using operator member function
6. Create two distance object with input values.
7. Sum the distance objects using overloaded + and store result in another distance
object
8. Call display member function.
9. Stop
Program
#include <iostream.h>
class distance
public: distance()
{ feet = inches = 0;
distance(int f, int i)
{ feet = f; inch = i;
void display()
{ cout << feet << "." << inch << "ft \n";
int main()
{ distance d1(10, 6), d2(11, 6), d3; cout << "Distance1 : ";
d1.display(); cout << "Distance2 : "; d2.display(); d3
= d1 + d2; cout << "Distance3 : "; d3.display(); if (d1
< d2) cout << "Distance1 is nearest";
else cout << "Distance2 is nearest";
return 0;
}
Distance1 : 10.6ft
Distance2 : 11.6ft
Distance3 : 22.0ft
Distance1 is nearest
Result
Thus two distance objects were added using operator overloading.
Aim
To create an array1d class and to overload operators + and to perform addition and
subtraction of one dimensional array.
Algorithm
1. Start
2. Declare class array1d with data members arr containing an array
3. Define getdata function to obtain input for array elements
4. Define display function to print array elements
5. Declare overloading of operator + and as friend to class array1d
6. Overload operator + as a non-member function to perform scalar addition on array
elements
7. Overload operator as a non-member function to perform array subtraction
8. Create array1d objects.
9. Call getdata function for each object
10. Invoke the overloaded operator + and on array1d objects
11. Call display member function.
12. Stop
Program
// 6d binary operator using friend function
#include <iostream.h>
class array1d
{ int arr[size];
void display()
{ for(int i=0; i<size; i++) cout << arr[i] << " ";
{ array1d tmp;
return tmp;
{ array1d tmp;
return tmp;
int main()
{ array1d B, C, K, S, T;
B.getdata(); C = 2 + B; cout
<< "2 + B = "; C.display();
T.getdata(); K = S - T; cout
<< "S - T = "; K.display();
return 0;
Output
2+B=34567
S - T = -2 2 5 6 2
Result
Thus one-dimensional array scalar addition and subtraction was performed using operator
overloading as a friend function.
Algorithm
1. Start
2. Define function template arrange to implement bubble sort with array argument
of template type
3. Declare different types of array containing unordered elements
4. Call arrange function for each array
5. Display array elements for each array
6. Stop
Program
// 7a function templates
#include <iostream.h>
arrange(x,6); arrange(y,6);
arrange(z,6);
Output
Sorted Arrays
-4 -0.4 I 0 0.7 a
1 1.9 d3 2.2 i
5 2.7 n
8 3.5 n
Result
Thus arrays of different types were sorted using a templated bubble sort routine.
Algorithm
1. Start
2. Declare a template class mystack with array data member st of template type
3. Define a default constructor that initializes top data member
4. Define push and pop operation with template arguments 5. Define function full
and empty to indicate stack full or empty
6. Create mystack objects of different types.
7. Invoke stack operations for each mystack object
8. Stop
Program
// 7b class template
#include <iostream.h>
public: mystack()
{ top = -1;
{ st[++top] = var;
T pop()
{ return st[top--];
bool empty()
} bool full()
} };
int main()
else s1.push(x);
else
S2.Push(i); }
return 0;
Output
Result
Thus stack operations push and pop were demonstrated on stack of different data types.
Algorithm
1. Start
2. Read two numbers a and b
3. Within try block, if b = 0 then raise exception for b
4. Otherwise execute arithmetic expression a / b
5. Define catch block to handle divide by zero exception
6. Stop
Program
// 8a Exception handling #include <iostream.h>
int main()
{ int a, b, x;
{ if (b == 0) throw(b);
catch(int i)
} return 0;
Result
Thus divide-by-zero error is handled using try, throw and catch mechanism.
Algorithm
1. Start
2. Declare mystack class with data members top and array st
3. Define exception classes full and empty for mystack class
4. Define push operation for mystack class. If stack is full then throw full exception
5. Define pop operation. If stack has no elements then throw empty exception
6. Create mystack object.
7. Perform a series of push and pop operation within try block.
8. On stack overflow and underflow raise full and empty exception.
9. Define catch handlers for full and empty type exceptions
10. Stop
Program
// 8b Exception using classes
#include <iostream.h>
class mystack
public:
mystack()
{ top = -1;
st[++top] = var;
int pop()
return st[top--];
} };
int main()
{ s1.push(11);
s1.push(22);
s1.push(33);
catch(mystack::full)
return 0;
Output
Poping stack
33
22
11
Result
Thus push and pop operations of a stack was demonstrated using exception handling.
Aim
To demonstrate functionality of C++ string class.
Algorithm
1. Start
2. Include header file string
3. Create objects of string class
4. Call member functions insert, append, erase, replace, swap, etc on string objects
5. Display the resultant string after each function call.
6. Stop
Program
// 9a STL string
#include <iostream>
int main()
cin >> s3; s4 = s3; if (s3 == s4) cout << "Strings s3 and s4 are identical
\n";
s4 = s1 + s2 + s3;
cout << "s1 + s2 + s3 = " << s4 << "\n"; string s5 = "ISO ";
s1.swap(s3);
cout << "Swap : s1 = " << s1 << " s3 = " << s3 << "\n"; cout << "Substring in s2 : "
<< s2.substr(7,3) << "\n"; cout << "a occurs at : " << s2.find_first_of('a') << "\n";
for(int i=0; i<s2.length(); i++) cout << s2[i];
return 0;
Output
Result
Thus strings were manipulated using various member functions of C++ string class
successfully.
Aim
To demonstrate the functionality of sequence container STL vector class.
Algorithm
1. Start
2. Include header file vector
3. Create a vector object v1 to store integers.
4. Use push_back member function to append elements onto v1
5. Delete last element in v1 using pop_back member function
6. Display first and last element of v1 using front and back member function
7. Display length of v1 using size member function
8. Display v1 elements using a loop
9. Stop
Program
// 9b STL vector
#include <iostream>
int main()
int data, i;
cout << "Enter 5 vector elements : "; for (i=0; i<v1.size(); i++)
cin >> v1[i];
v1.push_back(data); // Add element dynamically cout << "Current size: " << v1.size() <<
"\n"; cout << "First element : " << v1.front() << "\n"; cout << "Last element : " << v1.back()
<< "\n";
if (!v1.empty())
return 0;
Output
Enter 5 vector elements : 9 3 6 1 5
Current size: 6
First element : 9
Last element : 2
Vector elements : 9 3 6 1 5
Result
Thus a dynamic array with random access is implemented using STL vector.
Aim
To demonstrate functionality of bidirectional sequence container STL List class.
Algorithm
1. Start
2. Include header file list
3. Create list objects l2, l3 to store integers.
4. Declare an iterator first to step through list elements.
5. Insert odd numbers onto l2 from 1 to 10 using push_back member function
6. Insert even numbers onto l2 from 1 to 10 using push_front member function
7. Assign first to point to first element of a list using begin member function
8. Print list l2 and l3 elements using a loop
9. Sort list l3 using sort member function
10. Merge list l3 with l2 using merge member function
11. Print list l2 elements using a loop
12. Stop
Program
// 9c STL List
#include <iostream>
#include <list>
int main()
{ list <int> l2,l3; list <int>::iterator first; for (int i=1; i<10;
i+=2) l2.push_back(i);
return 0;
Output
List L2 : 1 3 5 7 9
List L3 : 8 6 4 2
Merged List 1 2 3 4 5 6 7 8 9
Result
Thus various operations are performed on STL list using its member function.
Aim
To demonstrate search operation on associative container STL map.
Algorithm
1. Start
2. Include header file map
3. Create map object m1 to store character and its corresponding ASCII value 4. Declare an
iterator ptr to step through map elements.
5. Populate map m1 using insert with pair member function
6. Read a character ch from the user
7. Search map m1 for the given key ch using find member function
8. If found then display corresponding ASCII value using member second
9. Stop
Program
// 9d STL Maps
#include <iostream>
#include <map>
int main()
{ map <char, int> m1; map <char, int>::iterator ptr; char ch;
Output
Enter key: P
ASCII value : 80
Result
Thus elements were inserted into a STL map and value retrieved for the given key.
Aim
To sort the given array using STL algorithms in descending order.
Algorithm
1. Start
2. Include header file algorithm and functional
3. Initialize a float array fdata with 5 elements
4. Sort the array using sort function with greater predicate
5. Print fdata elements using a loop
6. Stop
Program
#include <iostream>
#include <algorithm>
#include <functional>
int main()
{ float fdata[] = { 19.2, 87.4, -33.6, 55.0, 42.2 }; sort(fdata, fdata+5, greater<float>()); // sort
array cout << "Sorted array : "; for(int j=0; j<5; j++) cout << fdata[j] << " " ;
return 0;
}
Output
Result
Thus the given array is sorted using STL algorithms and function objects.
Aim
To write characters onto a file and to find number of vowels in it using character file
input/output operations.
Algorithm
1. Start
2. Include header file fstream
3. Declare a file object fp
4. Open file sample.txt in output mode using open function
5. Fetch character-by-character from console using get function
6. Write it onto file using put function,
7. Repeat steps 5-6 until end-of-file is encountered.
8. Close the file object fp using close function 9. Open file sample.txt in input mode
using open function 10. Initialize vc to 0.
11. Read character-by-character from file using get function
12. If character is a vowel, then increment vc.
13. Repeat steps 11-12 until end-of-file is encountered
14. Print vc
15. Close the file object fp using close function
16. Stop
Program
#include <iostream.h>
#include <fstream.h>
#include <ctype.h>
fp.close();
int vc = 0;
{ ch = fp.get(); switch(tolower(ch))
case 'u' :
vc++; break;
Output
^Z
No. of vowels : 10
Result
Thus a file was created and analyzed using get and put file I/O methods.
Aim
To copy an entire file using characteroriented file I/O with exception handling.
Algorithm
1. Start
2. Include header file fstream
3. Declare ifstream object src and ofstream object dst
4. Get source and destination filenames from user.
5. Within try block, open source file using src.
6. Open destination file using dst
7. If source file non-existent then raise an exception using throw
8. Read a character from source file using get function
9. Write that character onto destination file using put function
10. Repeat steps 8-9 until end-of-file is encountered
11. Define catch block to handle file-not-found exception
12. Stop
Program
#include <fstream.h>
#include <iostream.h>
int main()
while(src)
{ ch = src.get(); dst.put(ch);
} return 0;
Output
Result
Thus file is copied using character I/O with exception handling mechanisms.
Algorithm
1. Start
2. Include header file fstream
3. Declare class product with data members code, name and rate.
4. Define member function getdata, putdata and prodcode for product class
5. Create object for fstream and product class as fobj and p1 respectively
6. Display file operations as menu
7. Accept choice
8. If choice = 1 then
a. Open file invent.dat in append mode using open function
b. Obtain product details p1 using getdata member function
c. Write p1 onto file in binary format using write function
d. Close the file object fobj using close function
9. If choice = 2 then
a. Open file invent.dat in read mode
b. Accept product code pcode to be searched
c. Fetch a product record from file onto p1 using read function
d. Obtain code from p1 using prodcode member function
e. If p1's code = pcode then print product details using putdata
member function
f. Repeat steps c e until end-of-file is reached
g. Close the file object fobj using close function 10. Stop
#include <fstream.h>
#include <iostream.h>
class product
void putdata()
{ cout << "Name : " << name << "\n"; cout << "Rate : " << rate
<< "\n";
int prodcode()
{ return code;
} };
int main()
{ case 1:
p1.getdata();
fobj.close(); break;
case 2:
fobj.open("invent.dat", ios::in );
{ p1.putdata(); break;
} fobj.close(); break;
} return 0;
Name : hamam
Rate : 35.75
Result
Thus product details were appended to a file and accessed in a sequential manner.
Algorithm
1. Start
2. Include header file fstream
3. Declare class student with data members rollno, name, arrears and cgpa
4. Define member function getdata and display for student class
5. Create object for fstream and student class as fobj and s1 respectively
6. Display file operations as menu
7. Accept choice
8. If choice = 1 then
a. Open file placement.dat in append mode using open function
b. Obtain student details s1 using getdata member function
c. Write s1 onto file in binary format using write function
d. Close the file object fobj using close function
9. If choice = 2 then
a. Open file invent.dat in read mode
b. Accept roll number rno to be searched
c. Move file pointer to desired student record using seekg function
d. Fetch student record from file onto s1 using read function
e. Print s1 student details using display member function
f. Close the file object fobj using close function 10. Stop
Program
// 10d Object using random access
#include <fstream.h>
#include <iostream.h>
{ cout << "Enter rollno, name, arrear, cgpa : "; cin >> rollno >> name >>
arrear >> cgpa;
void display()
{ cout << "Name : " << name << "\n"; cout << "Arrears : " <<
arrear << "\n"; cout << "CGPA : " << cgpa << "\n"; } }; int main()
{ case 1:
s1.getdata();
fobj.open("placement.dat", ios::app|ios::binary);
fobj.close(); break;
case 2:
fobj.open("placement.dat", ios::in|ios::binary);
s1.display(); fobj.close();
break;
} return 0;
Output
1.Append 2.Display Enter your choice : 1
Name : vijai
Arrears : 6
CGPA : 6.2
Result
Algorithm
1. Start
2. Get number of disks, say n.
3. Push parameters and return address onto stack
4. If the stopping value has been reached then pop the stack to return to previous level
else move all except the final disc from starting to intermediate needle.
5. Move final discs from start to destination needle.
6. Move remaining discs from intermediate to destination needle.
7. Return to previous level by popping stack.
8. Stop
Program
// 11a Stack appln: towers of Hanoi
#include <iostream.h>
if(a == 1)
{ cout << "Move disc 1 from " << from; cout << " to " <<
to << "\n"; return;
} else
cout << "Move disc " << a << " from " << from; cout << " to " << to <<"\n";
tower(a-1, aux, from, to);
cout << "Tower of Hanoi \n"; cout << "Enter number of discs :
";
Output
Tower of Hanoi
Result
Thus n disks of different sizes are moved from rod A to rod C in an orderly manner.
Algorithm
1. Start
2. Declare structure node to store element, left child and right child for a binary search
tree
3. Declare class bst with member functions insert, preorder, inorder and postorder
4. Define insert member function to add an element
a. If first element, then place it as root
b. If element < root then traverse left subtree recursively until leaf
c. If element > root then traverse right subtree recursively until leaf
d. Insert new element as leaf
5. Define preorder member function to perform preorder traversal recursively
a. Visit root node
b. Visit left subtree
c. Visit right subtree
6. Define inorder member function to perform inorder traversal recursively
a. Visit left subtree
b. Visit root node
c. Visit right subtree
7. Define postorder member function to perform postorder traversal recursively
a. Visit left subtree
b. Visit right subtree
c. Visit root node
8. Create object tree for bst class
9. Display a choice menu in main function
10. Accept choice and invoke appropriate member function for tree object
11. Stop
#include<iostream.h>
#include <malloc.h>
};
if (root == NULL)
else
{ if (root != NULL)
}}
if (root != NULL)
}}
{ if (root != NULL)
}}
int main()
cout << "1.insert 2.preorder 3.inorder 4.postorder"; cout << " 0.Exit \n Enter your
choice : "; cin >> choice;
switch (choice)
tree.inorder(root); break;
else
tree.preorder(root);
} break;
else
tree.inorder(root);
} break;
else
tree.postorder(root);
case 0:
exit (0);
} return 0;
}
Result
Thus elements were inserted onto an empty binary search tree and traversed in different
ways.
Algorithm
1. Start
2. Define infinity to be a large number, say 999.
3. Declare class prim with requisite data members
4. Define create member function
a. Get number of vertices nodes.
b. Read adjacency matrix graph using a loop
c. For nodes with cost 0, assign infinity using a loop
5. Define findmst member function to determine minimum spanning tree
a. Initially all nodes are unselected
b. Find smallest edge from the graph connecting the vertex
c. Add that vertex
d. Print associated cost
e. Repeat the process until all vertices are added
f. Print total cost of Prim's MST
6. Create object pmst for prim class
a. Call create member function
b. Call findmst member function 7. Stop
Program
// 14a Prims MST
#include <iostream.h>
#define false 0
class prims
{ int graph[row][col];
int nodes;
public:
prims()
} void create();
void findmst();
};
void prims::create()
{ int i,j;
void prims::findmst()
selected[0] = true; ne = 0;
{ if(selected[i] == true)
{ if(selected[j] == false)
{ min = graph[i][j];
x = i; y = j;
}
}
} }
selected[y] = true;
cout << x+1 << " -> " << y+1 << " = " << graph[x][y] <<
"\n";
cost += graph[x][y]; ne = ne + 1;
prims pmst;
pmst.findmst(); return 0;
Output
Prims Algorithm
0241000200390
0400205013207
8409070060058
001
0 004610
Edges of Minimum Spanning Tree are :
7 -> 5 = 6
Cost of MST is : 16
Result
Thus minimum spanning tree for the given graph is determined using Prim's algorithm.
To determine minimum spanning tree for the given graph using Kruskal's algorithm
Algorithm
1. Start
2. Declare class kruskal with requisite data members
3. Define read member function
a. Get the number of vertices nodes
b. Read adjacency matrix cost using a loop
c. Update cost of an edge to 999 if it's 0 using a loop
d. Call kmst member function
4. Define kmst member function to determine minimum spanning tree
a. Find edge with minimum cost
b. Add edge if it does not form a cycle
c. Print cost of the edge
d. Repeat until all vertices are included
e. Print cost of minimum spanning tree
5. Create object k1 for kurskal class
a. Call read member function 6. Stop
Program
// 14b Kruskal's Algorithm
#include<iostream.h>
class kruskal
{ edges = 1; mincost = 0;
} void read();
};
void kruskal::read()
cout << "Enter adjacency matrix(cost) : \n"; for (i=1; i<=nodes; i++)
} kmst(cost, nodes);
while(parent[unvisited]) unvisited =
parent[unvisited];
if(unvisited != visited)
{ edges++;
cout << "edge(" << node1 << "->" << node2 << ") = "
024100020039
004002050132
078409070060
058001000461
0 Minimum cost
edges are: edge(1->4)
= 1 edge(6->7) = 1
edge(1->2) = 2
edge(3->4) = 2
edge(4->7) = 4
edge(5->7) = 6 MST
cost = 16
Result
Thus minimum spanning tree for the given graph is determined using Kruskal's
algorithm.
To find shortest path from a given vertex to all other vertices using Dijkstra algorithm
Algorithm
1. Start
2. Define infinity to be a large number, say 999.
3. Declare class dijkstra with requisite data members
4. Define read member function to obtain inputs
a. Get the number of vertex vertices
b. Read adjacency matrix adj using a loop
c. Get vertex to start with source.
5. Define initialize member function to do initial configuration
a. Initialize distance for each vertex to infinity
b. Initialize all nodes marked as false
c. Initialize all nodes as without any predecessor
6. Define unmarked member function
a. Return vertex with minimum distance amongst unmarked vertices
7. Define calculate member function
a. Call initialize member function
b. Update variables marked, distance and predecessor for adjacent
vertices
8. Define path member function to print path recursively
9. Define output member function
a. Call path member function to print path from source to each other
vertex
b. Print total distance from source to that vertex
10. Create object djk for dijkstra class
a. Call read member function
b. Call calculate member function
Program
// 15a Dijkstra's shortest path algorithm
#include<iostream.h>
class dijkstra
{ int adj[15][15];
};
void dijkstra::read()
cout << "Enter adjacency matrix for the graph : \n"; cout << "(For infinity enter " << infinity
<< ")\n";
for(int i=0; i<vertices; i++) for(int j=0; j<vertices; j++) cin >>
adj[i][j]; cout << "Enter the source vertex : ";
distance[source] = 0;
int dijkstra::unmarked()
return closest;
void dijkstra::calculate()
{ if(distance[i]>distance[closest]+adj[closest][i])
}}
count++;
}}
else if(predecessor[node] == -1) cout << "No path from " << source << "to " <<
node;
else
{ path(predecessor[node]);
void dijkstra::output()
{ if(i == source)
cout << "Shortest path from source vertex are : \n"; djk.output(); return 0;
A->A = 0
A->B = 2
A->D->C = 3
A->D = 1
A->D->E = 3
A->D->G->F = 6
A->D->G = 5
Result
Thus Dijkstra's algorithm to find the shortest path from a given vertex is implemented