Object-Oriented Programming & Data Structures (CS-201) : Lab Manual
Object-Oriented Programming & Data Structures (CS-201) : Lab Manual
Structures (CS-201)
Lab Manual
Prepared by
1.3 Activity
Write a program that takes the options from the user to perform addition, subtraction, multiplication,
square root and modulus of a number(s). (Hint: use switch operator for selection of calculator’s
function).
Note: after selection of appropriate option your program must ask the user to enter the required data
(in case of addition, subtraction and multiplication two numbers while one number for the other two
options i.e. square root and modulus).
1.4 Activity
C++ code to find Multiplication Table of a number using for loop and represents it in proper format.
1.5 Activity
Write a function that reverses elements stored in an array
Sample OUTPUT of the function
Enter length of the array: 5
Enter the elements of the array: 11 22 33 44 55
Input array is: 11 22 33 44 55
Reverse of the input array is: 55 44 33 22 11
Note: Actual input array elements are to be swapped i.e. in the above example, swap array element 0
with element 4 and so forth. Temporary array for reversing the elements is not allowed.
1.6 Activity
A palindrome is a number or a text phrase that reads the same backwards as forwards. For example,
each of the following five‐digit integers is a palindrome: 12321, 55555, 45554, and 11611. Write a
program that reads in a five‐digit integer and determines whether it is a palindrome. (Hint: use the
division and modulus operators to separate the number into its individual digits).
1.7 Activity
Write a program that would store one hundred random numbers, ranging from 0 to 99, in an array; and
displays the first repeating number in the array.
Hint: Numbers stored in the array has range [0, 99] and study the properties of % to figure out a way of
getting a random number in range [0, 99].
1.8 Activity
Write a program that computes and prints both the mean and the standard deviation of the input data.
The standard deviation of the n numbers ao, . . ., an, is defined by the formula
n 1
(a
i 0
i )2
n 1
where μ is the mean of the data. This means: square each deviation a[i] ‐ mean; sum those squares; take
the square root of that sum; divide that square root by n‐l.
1.9 Activity
` Write a program to add two nxn matrixes.
1.10 References:
1 Object-Oriented Programming in C++ by Robert Lafore
2 How to Program C++ by Deitel & Deitel
Lab No.2 Introductory concepts of Object Oriented
Programming
2.1 Objectives of the lab
Introducing the concepts of object-oriented programming and its implementation specifics such
as
6 classes and objects
7 access rights
8 data members and member functions
9 constructors
10 constructor overloading
2.2 Pre-Lab
2.2.1 Class
1 A set of homogeneous objects
2 An Abstract Data Type (ADT) -- describes a new data type
3 A collection of data items or functions or both
4 Represents an entity having
Characteristics
Attributes (member data)
Behavior
Functionality (member functions)
5 Provides a plan/template/blueprint
Is just a declaration
Is a description of a number of similar objects
6 Class Definition is a Type Declaration -- No Space is Allocated
void main()
{
complex c1;
c1.set_val(4,3);
c1.show();
}
2.2.5 Constructor
Special member function -- same name as the class name
initialization of data members
acquisition of resources
opening files
Does NOT return a value
Implicitly invoked when objects are created
Can have arguments
Cannot be explicitly called
Multiple constructors are allowed
If no constructor is defined in a program, default constructor is called
no arguments
constructors can be overloaded (two constructors with same name but having
different signatures)
#include <iostream.h>
class complex
{
private:
double re, im;
public:
complex() // simple method
{ re=0;
im=0;
}
complex(double r, double i):re(r), im(i) //initializer list
{}
2.2.7 In the above program, which constructors will be called for objects c1
and c2?
2.3 Post-Lab
2.3.1 Activity
Create a class, Heater that contains a single integer field, temperature. Define a constructor that takes
no parameters. The temperature field should be set to the value 15 in the constructor. Define the
mutators warmer and cooler, whose effect is to increase or decrease the value of the temperature by 5
respectively. Define an accessor method to return the value of temperature.
2.3.2 Activity
Create a class called BankAccount that models a checking account at a bank. The program creates an
account with an opening balance, displays the balance, makes a deposit and a withdrawal, and then
displays the new balance.
2.3.3 Activity
Modify your Heater class to define three new integer fields: min, max, and increment. The values of min
and max should be set by parameters passed to the constructor. The value of increment should be set
to 5 in the constructor. Modify the definitions of warmer and cooler so that they use the value of
increment rather than an explicit value of 5. Before proceeding further, check that everything works as
before. Now modify the warmer method so that it will not allow the temperature to be set to a value
larger than max. Similarly modify cooler so that it will not allow temperature to be set to a value less
than min. Check that the class works properly. Now add a method, setIncrement that takes a single
integer parameter and uses it to set the value of increment. Once again, test that the class works as you
would expect it to, by creating some Heater objects. Do things still work as expected if a negative value
is passed to the setIncrement method? Add a check to this method to prevent a negative value from
being assigned to increment.
2.3.4 Activity
Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 cent toll. Mostly they
do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that
have gone by, and of the total amount of money collected. Model this tollbooth with a class called
tollBooth. The two data items are a type unsigned int to hold the total number of cars, and a type
double to hold the total amount of money collected. A constructor initializes both of these to 0. A
member function called payingCar() increments the car total and adds 0.50 to the cash total. Another
function, called nopayCar(), increments the car total but adds nothing to the cash total. Finally, a
member function called display() displays the two totals. Make appropriate member functions const.
Include a program to test this class. This program should allow the user to push one key to count a
paying car, and another to count a nonpaying car. Pushing the [Escape] key should cause the program to
print out the total cars and total cash and then exit.
2.3.5 Activity
Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have
the form realPart + imaginaryPart * i
where i is 1
Write a program to test your class. Use floating-point variables to represent the private data of the class.
Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a
no-argument constructor with default values in case no initializers are provided. Provide public methods
that perform the following operations:
a) Add two Complex numbers: The real parts are added together and the imaginary parts are added
together.
b) Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of
the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of
the left operand.
c) Print Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
d) In class Complex, define a multiply method that returns the product of two Complex numbers.
Suppose you are trying to compute the product of two complex numbers a + bi and c + di. The real part
will be ac – bd, while the imaginary part will be ad+ bc. Modify Complex Test to test your solution.
2.3.6 Activity
Create a class Rectangle. The class has attributes length and width, each of which defaults to 1. Provide
methods that calculate the perimeter and the area of the rectangle. Provide set and get methods for
both length and width. The set methods should verify that length and width are each floating-point
numbers greater than or equal to 0.0 and less than 20.0. Write a program to test class Rectangle.
2.3.7 Activity
Create a class called Employee that includes three pieces of information as instance variables—a first
name, a last name, and a monthly salary. Your class should have a constructor that initializes the three
instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not
positive, set it to 0.0.Writea test application named EmployeeTest that demonstrates class Employee’s
capabilities. Create two Employee objects and display the yearly salary for each Employee. Then give
each Employee a 10% raise and display each Employee’s yearly salary again.
2.3.8 Activity
Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at
the store. An Invoice should include four pieces of information as instance variables—a part number, a
part description, a quantity of the item being purchased (type int), and a price per item (double).Your
class should have a constructor that initializes the four instance variables. Provide a set and a get
method for each instance variable. In addition, provide a method named getInvoiceAmount that
calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the
amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not
positive, it should be set to 0.0.Writea test application named InvoiceTest that demonstrates class
Invoice’s capabilities.
2.3.9 Activity
Create a class called Date that includes three pieces of information as instance variables—a month (type
int), a day (type int), and a year (type int). Your class should have a constructor that initializes the three
instance variables and assumes that the values provided are correct. Provide a set and a get method for
each instance variable. Provide a method displayDate that displays the month, day, and year separated
by forward slashes (/). Write a test application named DateTest that demonstrates class Date’s
capabilities.
2.4 References:
3 Class notes
4 Object-Oriented Programming in C++ by Robert Lafore (Chapter 6)
5 How to Program C++ by Deitel & Deitel (Chapter 6)
Lab No.3 Using the global scope resolution operator, passing
and returning objects to & from member functions
3.1 Objectives of the lab:
The purpose of this lab is to make you acquainted with the concepts such as
11 Defining member functions outside a class
12 Passing objects in function arguments
13 Returning objects from functions etc
3.2 Pre-Lab
void complex::show()
{
cout<<"Complex no: "<<re<<"+"<<im<<"i"<<endl;
}
void main()
{
complex c1(3, 4.3), c2(2, 4);
c3.add(c1, c2);
c3.show();
}
3.2.4 Make changes in the program to allow for a call to add function as
c3=c1.add(c2).
complex complex::negate()
{
complex temp;
temp.re= - re;
temp.im= - im;
return temp;
}
void complex::show()
{
cout<<"Complex no: "<<re<<"+"<<im<<"i"<<endl;
}
void main()
{
complex c1(3, 4.3), c2(2, 4);
c3=c1.negate();
c3.show();
}
3.3 Post-Lab
3.3.1 Activity
Create a class RationalNumber that stores a fraction in its original form (i.e. without finding the
equivalent floating pointing result). This class models a fraction by using two data members: an integer
for numerator and an integer for denominator. For this class, provide the following functions:
b) A two-argument constructor that initializes the numerator and denominator to the values sent
from calling function. This constructor should prevent a 0 denominator in a fraction, reduce or
simplify fractions that are not in reduced form, and avoid negative denominators.
c) A function AddFraction for addition of two rational numbers.
a c a * d b * c
b d b*d
Two fractions a/b and c/d are subtracted from each other as:
a c a * d b * c
b d b*d
a c a*c
*
b d b*d
a a*d
b c b*c
d
a. isGreater: should return a variable of type bool to indicate whether 1st fraction is
greater than 2nd or not.
b. isSmaller: should return a variable of type bool to indicate whether 1st fraction is
smaller than 2nd or not.
c. isGreaterEqual: should return a variable of type bool to indicate whether 1st fraction is
greater than or equal to 2nd or not.
d. isSmallerEqual: should return a variable of type bool to indicate whether 1st fraction is
smaller than or equal to 2nd or not.
e. isEqual: should return a variable of type bool to indicate whether 1st fraction is equal to
the 2nd fraction or not.
f. isNotEqual: should a true value if both the fractions are not equal and return a false if
both are equal.
3.3.2 Activity
Create a class called Time that has separate int member data for hours, minutes, and seconds. Provide
the following member functions for this class:
b. A 3-argument constructor to initialize the members to values sent from the calling function at the
time of creation of an object. Make sure that valid values are provided for all the data members. In
case of an invalid value, set the variable to 0.
d. A function AddTime for addition of two Time objects. Each time unit of one object must add into the
corresponding time unit of the other object. Keep in view the fact that minutes and seconds of
resultant should not exceed the maximum limit (60). If any of them do exceed, subtract 60 from the
corresponding unit and add a 1 to the next higher unit.
A main() programs should create two initialized Time objects and one that isn’t initialized. Then it
should add the two initialized values together, leaving the result in the third Time variable. Finally it
should display the value of this third variable.
3.3.3 Activity
Create a class called Distance containing two members feet and inches. This class represents distance
measured in feets and inches. For this class, provide the following functions:
a) A no-argument constructor that initializes the data members to some fixed values.
b) A 2-argument constructor to initialize the values of feet and inches to the values sent from the
calling function at the time of creation of an object of type Distance.
c) AddDistance function to add two distances: Feet and inches of both objects should add in their
corresponding members. 12 inches constitute one foot. Make sure that the result of addition
doesn’t violate this rule.
d) isGreater: should return a variable of type bool to indicate whether 1st distance is greater than
2nd or not.
e) isSmaller: should return a variable of type bool to indicate whether 1st distance is smaller than
2nd or not.
f) isGreaterEqual: should return a variable of type bool to indicate whether 1st distance is greater
than or equal to 2nd or not.
g) isSmallerEqual: should return a variable of type bool to indicate whether 1st distance is
smaller than or equal to 2nd or not.
h) isEqual: should return a variable of type bool to indicate whether 1st distance is equal to the
2nd distance or not.
i) isNotEqual: should a true value if both the distances are not equal and return a false if both are
equal.
3.3.4 Activity
Create a class called Martix that represents a 3x3 matrix. This matrix contains a two-dimensional
integer array of size 3x3. Provide the following member functions for this class:
b) A one-argument constructor to initialize the member matrix to the matrix sent as an argument
from the calling function.
3.3.5 Activity
Create a class called IntegerSet. Each object of class IntegerSet can hold integers in the range 0 through
49. A set is represented internally as an array of ones and zeros. Array element a[ i ] is 1 if integer i is in
the set. Array element a[ j ] is 0 if integer j is not in the set. The default constructor initializes a set to the
so-called “empty set,” i.e., a set whose array representation contains all zeros.
Provide member functions for the common set operations. For example,
1. Provide a unionOfIntegerSets member function that creates a third set which is the
set-theoretic union of two existing sets (i.e., an element of the third set’s array is set to 1 if that
element is 1 in either or both of the existing sets, and an element of the third set’s array is set to
0 if that element is 0 in each of the existing sets).
2. Provide an intersectionOfIntegerSets member function that creates a third set which is the
set-theoretic intersection of two existing sets (i.e., an element of the third set’s array is set to 0
if that element is 0 in either or both of the existing sets, and an element of the third set’s array is
set to 1 if that element is 1 in each of the existing sets).
3. Provide an insertElement member function that inserts a new integer k into a set (by setting
a[k] to 1).
4. Provide a deleteElement member function that deletes integer m (by setting a[m] to 0).
5. Provide a setPrint member function that prints a set as a list of numbers separated by spaces.
Print only those elements that are present in the set (i.e., their position in the array has a value
of 1).
6. Provide an isEqualTo member function that determines if two sets are equal.
Now write a driver program to test your IntegerSet class. Instantiate several IntegerSet objects. Test
that all your member functions work properly.
3.4 References:
6 Class notes
7 Object-Oriented Programming in C++ by Robert Lafore (Chapter 6)
8 How to Program C++ by Deitel & Deitel (Chapter 6)
Lab No.4 Operator Overloading
4.1 Objectives of the lab:
Introducing the concepts of operator overloading and overloading different operators such as
14 Arithmetic operators
15 Relational operators
16 Logical operators
17 Unary operators
4.2 Pre-Lab
void main()
{
complex c1(3, 4.3), c2(2, 4);
c1.show();
c2.show();
complex c3;
c3=c1+ c2; //Invocation of "+" Operator -- direct
//or
//c3=c1.operator+ (c2); //Invocation of "+" Operator -- Function
c3.show();
}
TYPE operator OP ()
{
body of function………
}
complex():re(0), im(0)
{}
complex(double r, double i):re(r), im(i)
{}
void show()
{
cout<<"complex number: "<<re<<"+"<<im<<"i"<<endl;
}
4.2.6 How can the above program be modified to allow for a statement like
c2=++c1;?
4.3 Post-Lab
4.3.1 Activity
Create a class RationalNumber that stores a fraction in its original form (i.e. without finding the
equivalent floating pointing result). This class models a fraction by using two data members: an integer
for numerator and an integer for denominator. For this class, provide the following functions:
b) A two-argument constructor that initializes the numerator and denominator to the values sent
from calling function. This constructor should prevent a 0 denominator in a fraction, reduce or
simplify fractions that are not in reduced form, and avoid negative denominators.
a c a * d b * c
b d b*d
Two fractions a/b and c/d are subtracted from each other as:
a c a * d b * c
b d b*d
a c a*c
*
b d b*d
a a*d
b c b*c
d
a. operator >: should return a variable of type bool to indicate whether 1st fraction is
greater than 2nd or not.
b. operator <: should return a variable of type bool to indicate whether 1st fraction is
smaller than 2nd or not.
c. operator >=: should return a variable of type bool to indicate whether 1st fraction is
greater than or equal to 2nd or not.
d. operator <=: should return a variable of type bool to indicate whether 1st fraction is
smaller than or equal to 2nd or not.
e. operator==: should return a variable of type bool to indicate whether 1st fraction is
equal to the 2nd fraction or not.
f. Operator!=: should a true value if both the fractions are not equal and return a false if
both are equal.
4.3.2 Activity
Create a class called Time that has separate int member data for hours, minutes, and seconds. Provide
the following member functions for this class:
b) A 3-argument constructor to initialize the members to values sent from the calling function at
the time of creation of an object. Make sure that valid values are provided for all the data
members. In case of an invalid value, set the variable to 0.
d) An overloaded operator+ for addition of two Time objects. Each time unit of one object must
add into the corresponding time unit of the other object. Keep in view the fact that minutes and
seconds of resultant should not exceed the maximum limit (60). If any of them do exceed,
subtract 60 from the corresponding unit and add a 1 to the next higher unit.
e) Overloaded operators for pre- and post- increment. These increment operators should add a 1
to the seconds unit of time. Keep track that seconds should not exceed 60.
f) Overload operators for pre- and post- decrement. These decrement operators should subtract a
1 from seconds unit of time. If number of seconds goes below 0, take appropriate actions to
make this value valid.
A main() programs should create two initialized Time objects and one that isn’t initialized. Then it
should add the two initialized values together, leaving the result in the third Time variable. Finally it
should display the value of this third variable. Check the functionalities of ++ and -- operators of this
program for both pre- and post-incrementation.
4.3.3 Activity
Create a class called Distance containing two members feet and inches. This class represents distance
measured in feets and inches. For this class, provide the following functions:
f) A no-argument constructor that initializes the data members to some fixed values.
g) A 2-argument constructor to initialize the values of feet and inches to the values sent from the
calling function at the time of creation of an object of type Distance.
a. operator+ to add two distances: Feet and inches of both objects should add in their
corresponding members. 12 inches constitute one feet. Make sure that the result of
addition doesn’t violate this rule.
a. operator >: should return a variable of type bool to indicate whether 1st distance is
greater than 2nd or not.
b. operator <: should return a variable of type bool to indicate whether 1st distance is
smaller than 2nd or not.
c. operator >=: should return a variable of type bool to indicate whether 1st distance is
greater than or equal to 2nd or not.
d. operator <=: should return a variable of type bool to indicate whether 1st distance is
smaller than or equal to 2nd or not.
a. operator==: should return a variable of type bool to indicate whether 1st Distance is
equal to the 2nd distance or not.
b. Operator!=: should a true value if both the distances are not equal and return a false if
both are equal.
4.3.4 Activity
Create a Point class has two coordinates x and y. Provide the following member functions:
a) Two constructors: one for initializing to fixed values and one for initializing to the values sent
from outside.
b) A function for displacing the object Point. Provide two values to this function which are added to
the x and y coordinates as displacements.
c) Functions for overloading the addition and subtraction operators: +=, +, -=, and unary and
binary-.
Now use the overloaded operator + for adding displacement to a Point. In this case, the
displacement will be represented by an object of type Point. So
P2=P1 + Disp; where P2, P1, and Disp all are instances of class Point.
4.3.5 Activity
Create a class called Martix that represents a 3x3 matrix. Create a constructor for initializing the matrix
with 0 values. Create another overloaded constructor for initializing the matrix to the values sent from
outside. Overload the + and += operators for addition of two matrices, == operator for checking the
equality of two matrices, and *operator for finding the product of the two matrices. Define all the
member functions outside the class.
4.3.6 Activity
Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have
the form realPart + imaginaryPart * i
where i is 1
Write a program to test your class. Use floating-point variables to represent the private data of the class.
Provide a constructor that enables an object of this class to be initialized when it is declared. Provide a
no-argument constructor with default values in case no initializers are provided. Provide public methods
that perform the following operations:
a) Add two Complex numbers: Overload the operators +, += for addition of two complex
numbers.
b) Subtract two Complex numbers: overload the operators -, -= for subtraction of two complex
numbers.
e) Print Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
f) Multiply two complex number: overload * and *= operators for multiplication of complex
numbers.
4.3.7 Activity
Let us model digital storage. Digital data is stored in the form of bits. 8 bits constitute one byte. Create a
class Storage that specifies the size of a file. This class has two integer data members: bits and bytes.
g) Provide a no-argument constructor to initialize the size of some file to 0 bits and 0 bytes.
h) Provide a two-argument constructor to initialize the size of a file to values specified at the time
of creation of an object.
i) Provide an overloaded operator + that is used to merge two files together in a third file.
j) Provide an overloaded operator += that is used to concatenate one file at the end of the other.
k) Provide overloaded post-increment and pre-increment operators to increment the size of a file
by one bit. (You must write the functions to accommodate statements like f2=++f1; and f2=f1++;
where f1 and f2 are instances of the class Storage)
l) Provide an overloaded operator > to determine whether one file is larger in size than the other.
4.4 References:
9 Class notes
10 Object-Oriented Programming in C++ by Robert Lafore(Chapter 8)
11 How to Program C++ by Deitel & Deitel (Chapter 8)
Lab No.5 Inheritance
5.1 Objectives of the lab:
Introducing the concepts of inheritance
18 Base and derived classes
19 Public inheritance
20 Private inheritance
21 Protected inheritance
5.2 Pre-Lab
5.2.1 Inheritance
void main()
{
B obj;
obj.print();
}
Q. In case of private and protected inheritance, would the public member num3
of class B be accessible to obj in main i.e. can we write obj.num3=2; ? If not,
why?
5.3 Post-Lab
5.3.1 Activity
Create a class called Point that has two data members: x- and y-coordinates of the point. Provide a
no-argument and a 2-argument constructor. Provide separate get and set functions for the each of the
data members i.e. getX, getY, setX, setY. The getter functions should return the corresponding values to
the calling function. Provide a display method to display the point in (x, y) format. Make appropriate
functions const.
Derive a class Circle from this Point class that has an additional data member: radius of the circle. The
point from which this circle is derived represents the center of circle. Provide a no-argument constructor
to initialize the radius and center coordinates to 0. Provide a 2-argument constructor: one argument to
initialize the radius of circle and the other argument to initialize the center of circle (provide an object of
point class in the second argument). Provide a 3-argument constructor that takes three floats to
initialize the radius, x-, and y-coordinates of the circle. Provide setter and getter functions for radius of
the circle. Provide two functions to determine the radius and circumference of the circle.
5.3.2 Activity
Derive a class Cylinder from the Circle class of activity 1. This class contains an additional data member:
height of cylinder. Provide appropriate constructors to initialize the center, radius, and height of the
cylinder. Provide functions to determine the area and volume of the cylinder. Area of a cylinder is 2πr*r+
2πr*h. Volume of cylinder is 2πr*r*h. Use the clac_area of circle class where required.
5.3.3 Activity
Imagine a publishing company that markets both book and audiocassette versions of its works. Create a
class publication that stores the title (a char string) and price (type float) of a publication. From this
class derive two classes: book, which adds a page count (type int); and tape, which adds a playing time
in minutes (type float). Each of these three classes should have a getdata() function to get its data from
the user at the keyboard, and a putdata() function to display its data. Determine whether public,
private, or protected inheritance should be used. Justify your answer.
Write a main() program to test the book and tape classes by creating instances of them, asking the user
to fill in data with getdata() and then displaying the data with putdata().
5.3.4 Activity
Start with the publication, book, and tape classes of activity 3. Add a base class sales that holds an array
of three floats so that it can record the dollar sales of a particular publication for the last three months.
Include a getdata() function to get three sales amount from the user, and a putdata() function to display
the sales figures. Alter the book and tape classes so they are derived from both publication and sales.
An object of class book or tape should input and output sales data along with its other data. Write a
main() function to create a book object and a tape object and exercise their input/output capabilities.
Determine whether book and tape classes should be publicly, privately, or protectedly inherited from
publication and sales classes. Justify your answer.
5.3.5 Activity
Assume that the publisher in activity 3 decides to add a third way to distribute books: on computer disk,
for those who like to do their reading on their laptop. Add a disk class that, like book and tape, is
derived from publication. The disk class should incorporate the same member functions as the other
classes. The data item unique to this class is the disk size: either 3-1/2 inches or 5-1/4 inches. You can
use an enum Boolean type to store this item, but the complete size should be displayed. The user could
select the appropriate size by typing 3 or 5.
5.3.6 Activity
Start with the publication, book, and tape classes of activity. Suppose you want to add the date of
publication for both books and tapes. From the publication class, derive a new class called publication2
that includes this member data. Determine whether inheritance or composition should be used. Then
change book and tape so they are derived from publication2 instead of publication. Make all the
necessary changes in member functions so the user can input and output dates along with the other
data. For the dates, you can use the date class from the Lab3 that stores a date as three ints, for month,
day, and year.
5.4 References:
12 Class notes
13 Object-Oriented Programming in C++ by Robert Lafore(Chapter 9)
14 How to Program C++ by Deitel & Deitel (Chapter 9)
Lab No.6 Multiple and Multilevel Inheritance
6.1 Objectives of the lab
Introducing the concepts of inheritance such as
22 Function overriding
23 Multiple inheritance
24 Multilevel inheritance
This lab also provides insight into composition and multifile programming.
6.2 Pre-Lab
#include <iostream.h>
class A
{
private:
int num1;
public:
A(): num1(0)
{}
void display()
{ cout<<"Number 1: "<<num1<<endl;
}
};
class B: public A
{
private:
int num2;
public:
B():num2(0)
{}
void display()
{
cout<<"Number 2: "<<num2<<endl;
}
};
void main()
{
B obj;
obj.display(); //display of class B called
obj.A::display(); //display of class A called
}
6.2.3 Example
#include <iostream.h>
class A
{
private:
int num1;
public:
A():num1(0)
{ cout<<"Class A constructor..."<<endl;
}
};
class B
{
private:
int num2;
public:
B():num2(0)
{
cout<<"Class B constructor..."<<endl;
}
};
void main()
{
C obj;
}
Q. if there are display functions in each of the three classes, which class’ display
function gets called if the statement obj.display(); gets executed? Write
statements to call the display function of all the three classes on obj.
6.2.5 Example
Header.h
#ifndef HEADER_H
#define HEADER_H
class Point
{
private:
int x, y;
public:
Point(): x(0), y(0)
{}
Point operator+(Point);
void display();
};
#endif
Header.cpp
#include <iostream.h>
#include "header.h"
void Point::display()
{
cout<<"("<<x<<","<<y<<")"<<endl;
}
Mainfile.cpp
#include <iostream.h>
#include "header.h"
void main()
{
Point p1(3, 4), p2(4, 2);
Point p3;
p3= p1 + p2;
cout<<"The result of Addition is: ";
p3.display();
}
6.3 Post-Lab
6.3.1 Activity
Create a class Employee that has a field for storing the complete name of employee (first and last
name), a field for storing the IDentification number of employee, and another field for storing his salary.
Provide
b) a 3-argument constructor for initializing the fields to values sent from outside. Use strcpy
function to copy one string into another.
c) a setter function (mutator) that sets the values of these fields by getting input from user.
Derive three classes from this employee class: Manager, Scientist, and Laborer. Manager class has an
additional data member of # of subordinates. Scientist class contains additional information about # of
publications. Laborer class is just similar to the employee class. It has no additional capabilities. Derive a
class foreman from the Laborer class that has an additional data member for storing the percentage of
quotas met by a foreman. Provide appropriate no-argument and n-argument constructors for all the
classes. Provide the overridden getter and setter functions here too to input and output all the fields.
Determine whether public, private, or protected inheritance should be used.
6.3.2 Activity
Create a class Student that contains information about a student’s name, semester, roll no, and date of
admission. To store the date of admission, again reuse the date class that you have already developed.
Determine whether you should use inheritance or composition.
Provide
a) a no-argument constructor for initializing the values of data members to some defaults.
b) a 4-argument constructor to initialize the data members sent from the calling function at the
time of creation of an object(date should be sent from outside in the form of a date object).
6.3.3 Activity
Derive a class Undergraduate from Student class of activity 2 that contains some additional information.
This information is about the semester gpa of a student and the credit points earned per semester. To
store this data, provide a 2D array (2x8 array since at maximum there are 8 semesters for an
undergraduate program). One dimension of the array should hold information about the SGPA of each
semester so far and the other dimension should hold the corresponding credit points earned in that
semester.
b) Provide overridden functions for getting and setting the data members.
c) Provide another function to calculate the CGPA of student on the basis of the information
provided by the 2D array.
Derive a class Graduate from Student class that also has the same additional information as the
Undergraduate class but in this case, the array is 2x4 since at maximum there are four semesters in a
Graduate program. There are two additional data members: one to store the title of the last degree held
and another to store the area of specialization in graduate program. Provide appropriate constructors
and overridden member functions.
6.3.4 Activity
Derive a class Complex2 from the class Complex of lab 4 that has additional member functions:
b) polar for calculating the phase of a complex number (a + bi) by atan(b/a) and magnitude by
sqrt(a2 + b2),
d) a rectangular function to get the rectangular coordinates back from phase and magnitude of a
complex number.
6.3.5 Activity
Redo all the questions of Lab5 using multi-file programming. Create a header file for your class
declaration, a .cpp file for class definition, and another .cpp file containing main function.
6.4 References
15 Class notes
16 Object-Oriented Programming in C++ by Robert Lafore (Chapter 9)
17 How to Program C++ by Deitel & Deitel (Chapter 9)
Lab No.7 Dynamic Memory Allocation and miscellaneous
topics
7.1 Objectives of the lab:
This lab covers some miscellaneous topics such as
Dynamic memory allocation
Copy Constructor (Deep & Shallow copy)
Const members and objects
Cascaded function calls
Static data members, member functions, and objects
7.1.1 Activity
Study the following programs, execute them, and determine what possibly the
cause of error. Write the additional code to make these programs run.
PROGRAM 1
#include <iostream.h>
#include <string.h>
class student
{
private:
char *name;
int roll;
int semester;
public:
student(char *n, int r, int s): roll(r), semester(s)
{
name=new char[strlen(n) + 1];
strcpy(name, n);
}
void set()
{
cout<<"Enter name: "<<endl;
cin>>name;
cout<<"Enter roll no: "<<endl;
cin>>roll;
cout<<"Enter semester: "<<endl;
cin>>semester;
}
void show()
{
cout<<"Name: "<<name<<endl;
cout<<"Roll NO: "<<roll<<endl;
cout<<"Semester: "<<semester<<endl;
}
~student()
{
delete[] name;
}
};
void main()
{
student s1("Bjarne Stroustrup", 3, 3);
s1.show();
{
student s2=s1;
s2.show();
}
s1.show();
}
PROGRAM 2
#include <iostream.h>
#include <string.h>
class student
{
private:
char *name;
int roll;
int semester;
public:
void set()
{
cout<<"Enter name: "<<endl;
cin>>name;
cout<<"Enter roll no: "<<endl;
cin>>roll;
cout<<"Enter semester: "<<endl;
cin>>semester;
}
void show()
{
cout<<"Name: "<<name<<endl;
cout<<"Roll NO: "<<roll<<endl;
cout<<"Semester: "<<semester<<endl;
}
~student()
{
delete[] name;
}
};
void main()
{
student s1("Bjarne Stroustrup", 3, 3);
s1.show();
student s2(s1);
s2.show();
s2.set();
cout<<"After setting s2:"<<endl;
cout<<"Data of student S1"<<endl;
s1.show();
7.1.2 Activity
Create a class called student. This class contains data members for name, roll no, and CGPA of a student.
1. Provide a no-argument constructor for initializing the data members to some fixed value.
2. Provide a 2-argument constructor to initialize the data members to the values sent from the
calling function.
3. Provide separate setter functions for setting each data member. These functions should take
the values from user at run-time.
4. Provide separate getter functions for each data member. The getter functions should return the
value of the corresponding fields.
Let us suppose that we want to keep information about average CGPA of students in a particular
department. Make appropriate changes in the class to handle this extra information (Hint: provide static
data members for average CGPA and no of students and set the values for these members in
constructor). Provide a static function to display this additional information.
7.1.3 Activity
Create a class called employee. This class maintains information about name (char*), department
(char*), salary (double), and period of service in years (double).
1. Provide a no-argument constructor to initialize the data members to some fixed values.
2. Provide a 4-argument constructor to initialize the members to values sent from calling function.
(You have to make dynamic allocation for both name and department data members in
constructor.)
3. Provide a copy-constructor that performs the deep copy of the data members.
4. Provide an input function that takes all the values from user during run-time.
5. Provide a display function that displays all the information about a specific student to user.
6. Provide a destructor to free the memory allocated to name and department in constructor.
7.1.4 Activity
Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have
the form realPart + imaginaryPart * i
where i is 1
Write a program to test your class. Use floating-point variables to represent the private data of the class.
1. Provide a constructor that enables an object of this class to be initialized when it is declared.
2. Provide a no-argument constructor with default values in case no initializers are provided.
3. Print Complex numbers in the form (a, b), where a is the real part and b is the imaginary part.
4. Provide separate setter functions for setting the real and imaginary portions of this class.
5. Provide separate getter functions for both the fields that must return the values of real and
imaginary parts of a complex number.
Note: Write the setter functions as well as the print function in a manner that allows for the cascaded
calls of these functions.
7.2 References:
18 Class notes
19 Object-Oriented Programming in C++ by Robert Lafore (Chapter 6)
20 How to Program C++ by Deitel & Deitel (Chapter 7)
Lab No.8 Friend Functions and Classes
8.1 Objectives of the lab:
Introducing the concepts of friendship such as
25 Friend functions
26 Friend classes
8.2 Pre-Lab
8.2.2 Example
#include <iostream.h>
class test
{
private:
int data;
public:
test(): data(0)
{}
void show()
{ cout<<data<<endl;
}
void main()
{
test t;
set_data(t); //called like normal function
t.show();
}
8.2.4 Example
#include <iostream.h>
#include <string.h>
class A
{
private:
int x;
friend class B;
public:
A(): x(0)
{}
void showA()
{
cout<<x<<endl;
}
};
class B
{
private:
int y;
public:
B(): y(0)
{}
void main()
{
A obja;
B objb;
objb.showB(obja);
cout<<"after calling showB()..."<<endl;
obja.showA();
}
8.3 Post-Lab
8.3.1 Activity
Create a class RationalNumber that stores a fraction in its original form (i.e. without finding the
equivalent floating pointing result). This class models a fraction by using two data members: an integer
for numerator and an integer for denominator. For this class, provide the following functions:
b) A two-argument constructor that initializes the numerator and denominator to the values sent
from calling function. This constructor should prevent a 0 denominator in a fraction, reduce or
simplify fractions that are not in reduced form, and avoid negative denominators.
a c a * d b * c
b d b*d
Two fractions a/b and c/d are subtracted from each other as:
a c a * d b * c
b d b*d
a c a*c
*
b d b*d
a a*d
b c b*c
d
a. operator >: should return a variable of type bool to indicate whether 1st fraction
is greater than 2nd or not.
b. operator <: should return a variable of type bool to indicate whether 1st fraction
is smaller than 2nd or not.
c. operator >=: should return a variable of type bool to indicate whether 1st
fraction is greater than or equal to 2nd or not.
d. operator <=: should return a variable of type bool to indicate whether 1st
fraction is smaller than or equal to 2nd or not.
b. Operator!=: should a true value if both the fractions are not equal and return a
false if both are equal.
8.3.2 Activity
Create a class called Time that has separate int member data for hours, minutes, and seconds. Provide
the following member functions for this class:
b) A 3-argument constructor to initialize the members to values sent from the calling function at
the time of creation of an object. Make sure that valid values are provided for all the data
members. In case of an invalid value, set the variable to 0.
a. An overloaded operator+ for addition of two Time objects. Each time unit of one object
must add into the corresponding time unit of the other object. Keep in view the fact
that minutes and seconds of resultant should not exceed the maximum limit (60). If any
of them do exceed, subtract 60 from the corresponding unit and add a 1 to the next
higher unit.
b. Overloaded operators for pre- and post- increment. These increment operators should
add a 1 to the seconds unit of time. Keep track that seconds should not exceed 60.
c. Overload operators for pre- and post- decrement. These decrement operators should
subtract a 1 from seconds unit of time. If number of seconds goes below 0, take
appropriate actions to make this value valid.
A main() programs should create two initialized Time objects and one that isn’t initialized. Then it
should add the two initialized values together, leaving the result in the third Time variable. Finally it
should display the value of this third variable. Check the functionalities of ++ and -- operators of this
program for both pre- and post-incrementation.
8.3.3 Activity
Create a class called Distance containing two members feet and inches. This class represents distance
measured in feets and inches. For this class, provide the following functions:
a) A no-argument constructor that initializes the data members to some fixed values.
b) A 2-argument constructor to initialize the values of feet and inches to the values sent from the
calling function at the time of creation of an object of type Distance.
a. operator+ to add two distances: Feet and inches of both objects should add in their
corresponding members. 12 inches constitute one feet. Make sure that the result of
addition doesn’t violate this rule.
c. operator >: should return a variable of type bool to indicate whether 1st distance is
greater than 2nd or not.
d. operator <: should return a variable of type bool to indicate whether 1st distance is
smaller than 2nd or not.
e. operator >=: should return a variable of type bool to indicate whether 1st distance is
greater than or equal to 2nd or not.
f. operator <=: should return a variable of type bool to indicate whether 1st distance is
smaller than or equal to 2nd or not.
g. operator==: should return a variable of type bool to indicate whether 1st Distance is
equal to the 2nd distance or not.
h. operator!=: should a true value if both the distances are not equal and return a false if
both are equal.
8.3.4 Activity
Let us model digital storage. Digital data is stored in the form of bits. 8 bits constitute one byte. Create a
class Storage that specifies the size of a file. This class has two integer data members: bits and bytes.
a) Provide a no-argument constructor to initialize the size of some file to 0 bits and 0 bytes.
b) Provide a two-argument constructor to initialize the size of a file to values specified at the time
of creation of an object.
a. Provide an overloaded operator + that is used to indicate the size of the resultant file
obtained as a result of merging two files.
b. Provide an overloaded operator += that is used to indicate the size of a file if another
file is concatenated at the end of it.
d. Provide an overloaded operator > to determine whether one file is larger in size than
the other or not. This function should return a bool type variable.
8.3.5 Activity
Create a class called IntegerSet. Each object of class IntegerSet can hold integers in the range 0 through
49. A set is represented internally as an array of ones and zeros. Array element a[ i ] is 1 if integer i is in
the set. Array element a[ j ] is 0 if integer j is not in the set. The default constructor initializes a set to the
so-called “empty set,” i.e., a set whose array representation contains all zeros.
Provide friend functions for the common set operations. For example,
1. Provide an operator + non-member function that creates a third set which is the set-theoretic
union of two existing sets (i.e., an element of the third set’s array is set to 1 if that element is 1
in either or both of the existing sets, and an element of the third set’s array is set to 0 if that
element is 0 in each of the existing sets).
2. Provide an operator* function that creates a third set which is the set-theoretic intersection of
two existing sets (i.e., an element of the third set’s array is set to 0 if that element is 0 in either
or both of the existing sets, and an element of the third set’s array is set to 1 if that element is 1
in each of the existing sets).
3. Provide an insertElement member function that inserts a new integer k into a set (by setting
a[k] to 1).
4. Provide a deleteElement member function that deletes integer m (by setting a[m] to 0).
5. Provide a setPrint member function that prints a set as a list of numbers separated by spaces.
Print only those elements that are present in the set (i.e., their position in the array has a value
of 1).
6. Provide an operator== non-member function that determines if two sets are equal.
9.2.1 Polymorphism
A generic term that means 'many shapes'. In C++ the simplest form of Polymorphism is
overloading of functions.
Ability for objects of different classes to respond differently to the same function call
Base-class pointer (or reference) calls a virtual function
C++ chooses the correct overridden function in object
Attained by making a function virtual in base class.
Keyword virtual is used in function declarator.
Keyword virtual is not necessary to be used in derived classes. The overridden functions
in derived classes are virtual automatically.
9.2.2 Example
#include<iostream.h>
class shape
{
public:
virtual void draw()
{
cout<<"Shape class"<<endl;
}
};
class triangle: public shape
{
public:
void draw()
{
cout<<"Triangle class"<<endl;
}
};
class rectangle: public shape
{
public:
void draw()
{
cout<<"Rectangle class"<<endl;
}
};
void main()
{
shape *sh;
triangle t;
rectangle r;
circle c;
sh=&t; sh->draw();
sh=&r; sh->draw();
sh=&c; sh->draw();
}
Q. What is the effect of the following statement?
shape s;
9.3 Post-Lab
9.3.1 Activity
Define an abstract base class shape that includes protected data members for area and volume of a
shape, public methods for computing area and volume of a shape (make the functions virtual), and a
display function to display the information about an object. Make this class abstract.
Derive a concrete class point from the shape class. This point class contains two protected data
members that hold the position of point. Provide no-argument and 2-argument constructors. Override
the appropriate functions of base class.
Derive a class Circle publicly from the point class. This class has a protected data member of radius.
Provide a no-argument constructor to initialize the fields to some fixed values. Provide a 3-argument
constructor to initialize the data members of Circle class to the values sent from outside. Override the
methods of base class as required.
Derive another class Cylinder from the Circle class. Provide a protected data member for height of
cylinder. Provide a no-argument constructor for initializing the data members to default values. Provide
a 4-argument constructor to initialize x- and y-coordinates, radius, and height of cylinder. Override the
methods of base class.
9.3.3 Activity
Create a class called publication that stores the title (char array) and price (float) of a publication. From
this class derive tow classes: book, which adds a page count (type int) and tape, which adds a playing
time in minutes (type float). Each of the three classes should have a getdata() function to get its data
form the user at the keyboard and a putdata() function to display the data.
Write a main program that creates an array of pointers to publication. In a loop, ask the user for data
about a particular type of book or tape to hold the data. Put the pointer to the object in the array. When
the user has finished entering the data for all books and tapes, display the resulting data for all the
books and tapes entered, using a for loop and a single statement such as
pubarr[j]->putdata();
To display the data form each object in the array.
9.4 References:
24 Class notes
25 Object-Oriented Programming in C++ by Robert Lafore
26 How to Program C++ by Deitel & Deitel
Lab No.10 Lists, Stacks and Queues
10.1 Objectives of the lab:
Introducing the concepts of some linear data structures such as
31 Linear lists
32 Stack
33 Linear Queue
34 Circular Queue
10.2 Pre-Lab
10.2.1 Stack
1 Stores arbitrary objects
2 Insertions and deletions follow the Last-in-First-out scheme
3 Also known as LIFO or FILO structure
4 Main Stack Operations
o Push (Object o): Inserts element o
o Pop (Object o): Removes element o
5 Auxiliary stack operations
o Top (): Returns the last inserted element without removing it.
o Size(): Returns the number of stored elements
o IsEmpty(): A Boolean value indicating whether no elements are stored
10.4.1 Activity
Implement a complete array based Stack.
10.4.2 Activity
Implement a complete array based Queue.
10.4.3 Activity
Implement a circular-queue whose front and rear are connected together. Justify what is the problem in
linear queue due to which we need a circular queue.
10.4.4 Activity
Implement a list using array with following operations:
1 Traversal
2 Insertion at beginning
3 Insertion at end
4 Insertion at nth location
5 Deletion from beginning
6 Deletion from end
7 Deletion from nth location
8 Searching an element
10.4.5 Activity
Create a structure for book that contains information about title, price, edition, and no of pages of the
book. Use your program of activity 1 to push and pop books on a stack.
10.4.6 Activity
Let us model the flow of customers in a queue. Create a structure called Person that contains
information about first name, last name, age, sex, and address of a person. Use your program of activity
2 to enqueue and dequeue Persons from a queue.
10.5 References
27 Class notes
28 Data Structures, Schaum’s outline series
29 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.11 Linked Lists
11.1 Objectives of the lab:
Introducing the concepts of some linear data structures such as
35 Single Linked lists
36 Operation on single linked list
37 Stack and Queue using linked list
11.2 Pre-Lab
11.3.1 Activity
Implement complete linked list containing the following operations:
9 Traversal
10 Insertion at beginning
11 Insertion at end
12 Insertion at nth location
13 Deletion from beginning
14 Deletion from end
15 Deletion from nth location
16 Searching an element
11.3.2 Activity
Implement stack using single linked list.
11.3.3 Activity
Implement queue using single linked list.
11.3.4 Activity
Write a program to remove duplicates from a singly linked list.
11.3.5 Activity
Write a program that creates a linked list object of 10 characters and then creates a second list
object containing a copy of the first list, but in reverse order.
11.3.6 Activity
Write a program that concatenates two linked list objects of characters. The program should
include function concatenate, which takes references to both list objects as arguments and
concatenates the second list to the first list.
11.3.7 Activity
Write a program that uses a stack object to determine if a string is a palindrome (i.e., the string is
spelled identically backwards and forwards). The program should ignore spaces and punctuation.
11.4 References:
30 Class notes
31 Data Structures, Schaum’s outline series
32 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.12 Applications of Stacks
12.1 Objectives of the lab
Introducing the applications of stack such as:
42 Symbol balancing
43 Infix to postfix conversion
44 Expression evaluation
12.2 Pre-Lab
1 Ignore other characters, just check for balancing of parentheses, brackets, & braces.
2 A simple Algorithm
o Make an empty Stack
o Read characters until end of file
o If the character is an opening symbol, push it onto the stack.
o If it is a closing symbol, then if the stack is empty report an error.
o Otherwise pop the stack. If the popped symbol is not the corresponding opening
symbol, then report an error.
o At the end of file if the stack is not empty, report an error
{
if C is an operand
else // C is an operator
12.3 Post-Lab
12.3.1 Activity
Implement the algorithm of symbol balancing using array-based as well as single linked list.
12.3.2 Activity
Implement the algorithm for infix to postfix conversion array-based as well as single linked list.
12.3.3 Activity
Implement the algorithm for expression evaluation array-based as well as single linked list.
12.4 References
33 Class notes
34 Data Structures, Schaum’s outline series
35 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.13 Doubly Linked Lists
13.1 Objectives of the lab
Introducing the concepts of some double linked list such as
45 Basics of double linked list
46 Operations on double linked list
13.2 Pre-Lab
13.3 Post-Lab
13.3.1 Activity
Implement complete double linked list containing the following operations:
13.4 References:
36 Class notes
37 Data Structures, Schaum’s outline series
38 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.14 Circularly Linked Lists and their Applications
14.1 Objectives of the lab:
Introducing the concepts of circular linked list such as
47 Basics of circular linked lists
48 Operations on circular linked lists
49 Applications of circular linked lists
14.2 Pre-Lab
14.3 Post-Lab
14.3.1 Activity
Implement complete circular single linked list containing the following operations:
26 Traversal
27 Insertion at beginning
28 Insertion at end
29 Insertion at nth location
30 Deletion from beginning
31 Deletion from end
32 Deletion from nth location
33 Searching an element
14.3.2 Activity 14.2
Implement complete circular double linked list containing the following operations:
34 Traversal
35 Insertion at beginning
36 Insertion at end
37 Insertion at nth location
38 Deletion from beginning
39 Deletion from end
40 Deletion from nth location
41 Searching an element
14.4 References:
39 Class notes
40 Data Structures, Schaum’s outline series
41 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.15 Trees and their Operations
15.1 Objectives of the lab
Introducing the concepts of trees such as
50 Basics of trees
51 Operations on trees
15.2 Pre-Lab
15.2.1 Trees
1 Represent hierarchical relationship between elements
File structure
Family tree
Organization tree
15.3.1 Activity
Implement a binary search tree with following operations
2 Insertion
3 Deletion
4 Traversal (using recursion)
3. Pre-order
4. Post-order
5. In-order
5 Searching
6 Sorting
15.4 References:
42 Class notes
43 Data Structures, Schaum’s outline series
44 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia
Lab No.16 Tree Traversal using Stacks
16.1 Objectives of the lab:
Introducing some more concepts of trees such as
52 Traversal of tree using stack-based approach
16.2 Pre-Lab
2 Initially:
CUR=root
(a) Follow the left path of CUR, process each node on the path, and push each
right child (if any) onto the stack. Traversing ends when a node with no left child
is encountered.
(b) Pop and assign to CUR the top element of stack. If CUR!=NULL, then repeat
step (a), otherwise Exit.
2 Initially:
CUR=root
(a) Follow the left path of CUR and push each node onto the stack. Stop when a
node with no left child is pushed onto the stack.
(b) Pop and process the nodes on stack. If a NULL is popped, Exit. If a node with
a right child is processed, set CUR=CUR->right and repeat step (a).
2 Initially:
push NULL on stack
CUR=root
(a) Follow the left path of CUR and push each node onto the stack. If the node
has a right child R, push –R onto the stack.
(b) Pop and process positive nodes on stack. If a NULL is popped, Exit. If a node
with a right child is processed, set CUR= -R and repeat step (a).
16.3 Post-Lab
16.3.1 Activity
Implement the stack-based algorithms for
1. In-order traversal
2. Pre-order traversal
3. Post-order traversal
16.4 References:
45 Class notes
46 Data Structures, Schaum’s outline series
47 Data structures and algorithms in C++ by Micheal T. Goodrich and Roberto
Tamassia