DS Lab Manual (Fall)
DS Lab Manual (Fall)
LAB MANUAL
V1.1 Spring 2021
Lab Designers
10 Mid Term
16 Final Term
Department of Software Engineering/Computer Science
1
Department of Software Engineering/Computer Science
A program is a set of instructions that processes data which is given as input to it. If we
need to develop a good (efficient) program, we need to organize data in computer’s memory in
effective way. This organized data is called a Data Structure.
Study of computer science includes the study of how data (information) is organized in
computer and how it can be manipulated and utilized by programs. It is extremely important for
you to understand the concepts of data (information) organization and manipulation. Data
structures for storing information are lists, stacks, queues, trees, graphs and tables.
Assume you have a program which is used to store information about the employees of
some organization, when this program starts its execution we are not sure that how many number
2
Department of Software Engineering/Computer Science
of employee records will be stored in this program. Therefore how much memory is required for
this program is dependent on the fact that how many records we will enter when program will be
executing. So memory required by program is to be estimated at program execution time, so we
will need a memory allocation mechanism which is called dynamic memory allocation for this
program, which should allocate and de allocate memory at runtime according to requirements of
program.
3
Department of Software Engineering/Computer Science
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
Example:
An array named “Numbers” containing five elements of type integer (int) can be defined as:
Figure 1 represents the logical representation of this array, which shows elements of the array are
located consecutively:
When an array is declared in a local scope, if not specified otherwise, its elements are not
initialized by some value by default. Elements of global and static arrays are automatically
initialized by their default values (zeros for numeric data types).
4
Department of Software Engineering/Computer Science
If we want to initialize any global or local array by assigning some values to its element
we can do so. Following example represents the initialization of an array of 5 integer elements.
Example:
For example, to store the value 25 in the third element of Numbers, we could write the following
statement:
To pass the value of the third element of Numbers to a variable called a, we could write:
a = Numbers[2];
5
Department of Software Engineering/Computer Science
Above code will create a pointer variable named “pointer” which is pointing to a dynamic
variable of int type created by new operator. After the creation of variable a constant value 5 is
assigned to this variable using the pointer variable, because a dynamic variable does not have a
name to be referenced. When dynamic variable is used and is no more required, we can de
allocate its memory by using delete operator. With delete operator we use name of pointer
variable which is pointing to that dynamic variable required to be de allocated.
int size;
delete [] array;
new and delete operators can be used with a user defined type or class/struct as well. Assume
following is a class definition for which we need to create a dynamic object.
class Rectangle {
private: int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
6
Department of Software Engineering/Computer Science
Following code segment creates and destroys a dynamic object of above described class.
7
Department of Software Engineering/Computer Science
Indices of first subscripts are logical represented as rows and indices of second subscripts
are logically represented as columns. Now for example the way to reference the second element
vertically and fourth horizontally in an expression would be:
numbers [1][3];
Following figure 3 shows the element in the two dimensional array which is referred above.
To assign some value to elements of a two-dimensional array, we simply use two subscripts:
numbers[1][3] = 7;
To initialize a two-dimensional array, it is easiest way to use nested braces, with each set of
numbers representing a row:
int numbers[3][5] =
{{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2 };
We may initialize a two dimensional array of type int by values 0 by using following statement.
Remember that we have to specify the size of array in terms of rows and columns for proper
initialization.
int numbers[3][5] = { 0 };
8
Department of Software Engineering/Computer Science
Two dimensional arrays can be created and accessed using pointers to pointers. Following code
segment provides information that such array usage.
The above code segment declares an array of integer pointers to integer pointers. The first thing
we do is then make a point to an array of integer pointers. Then we have to loop through all of
those pointers and assign them to an array of ints of size width. What this does is create an array
in the size of Height x Width.
Multi-dimensional arrays may be larger than two dimensions, arrays which have 3 dimensions
are called multi-dimensional arrays, they can be logical represented by a cube shape. An array
representing product sales for departmental stores at five cities/locations, 10 products and
containing sale information for 7 years can be declared as:
float productSales[5][10][7];
Where first subscript represents the location/city number, second subscript represents the product
number and third subscript represents the year number for which product sale information will be
stored in this array.
Three dimensional arrays cannot be easily initialized as compared to two dimensional arrays
initialization, so normally they are initialized by zero/blank value and then further initialization is
performed by using nested loops.
9
Department of Software Engineering/Computer Science
After completion of addition operation for two arrays, value of this variable should be
displayed on computer screen.
5.3.1 Task-1
Make a list of features of static and dynamic arrays in C++, which should provide
difference between these two types of arrays.
5.3.2 Task-2
Provide comparison between dynamic memory allocation schemes in C++ and Java,
provide differences and similarities.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
6.2 Editing, Compiling and Running programs in Visual Studio 2017 [Expected
time = 5mins]
You are required to use Microsoft Visual Studio 2017 environment for programming on data
structures. It is expected that you are already familiar with this environment in your courses of
Computer Programming and Object Oriented Programming. You should be able to write code in
source code files (cpp files) and perform compilation of code. Beside that you are also required
to be proficient in performing line by line debugging and break point based debugging to remove
the errors from your code.
Following program represents the concept related to static and dynamic arrays; you are
required to type this program in editor of Visual Studio 2017, compile and run to see the output
of this program. Figure 3 shows the source code window of this program in Visual Studio 2017.
10
Department of Software Engineering/Computer Science
Figure 3: A program about static and dynamic arrays in Visual Studio 2017
Output of this program is shown in figure 4, when program is compiled and executed.
11
Department of Software Engineering/Computer Science
Figure 6: Output window displaying values of elements of two dimensional arrays in Microsoft
Visual Studio 2017
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
12
Department of Software Engineering/Computer Science
7.1 Write a C++ program to create two pointers of integer type, now take values in these
pointers and pass them to a function. Function will update both the values by adding “1” to them.
Display the updated values in main.
7.2 Create a dynamic array of user defined size. Now take input in array from user. Take a new
(integer) value from user and search that how many times the entered number is present in the
array.
7.3 Write a program to create a dynamic array of user defined size. Array should be of character
type. Write a function ChangeCase() that should convert all the small alphabets to capital and
vice versa. All array operations should be done using pointers.
7.4 Write a program to create a dynamic array of user defined size. Size should be in the range
of 0 to 15. Write a function FindLarge that should ask user to enter a non-negative number.
Function should find the next largest number than the input number in the list.
Sample input:
Enter size: 5
After insertion:
13 4 55 29 32
Sample output:
Enter number: 15
Next largest number from 15 is: 29
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
13
Department of Software Engineering/Computer Science
1. http://www.cplusplus.com/doc/tutorial/
2. http://www.learncpp.com/
3. http://www.tutorialspoint.com/cplusplus/
14
Department of Software Engineering/Computer Science
15
Department of Software Engineering/Computer Science
1. Introduction
In this lab, you will learn about the dynamic list implementation using arrays in C++,
ADT (Abstract Data Types) and Stack ADT. A list is a collection of items of the same type. The
list can be based on numbers (natural or floating-point), text, dates, times, or such values as long
as the items are of the same type.An abstract data type (ADT) is a precise model for a certain
class of data structures that have similar actions; or for definite data types of one or more
programming languages that have similar semantics. Stack is a data structure which allows
placement of elements in Last in First out (LIFO) fashion.
16
Department of Software Engineering/Computer Science
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.
4.1 Dynamic Lists in C++ using Arrays
Dynamic list in C++ can be designed using arrays. We may add or remove elements from this
list during execution of program and arrays size can controlled at program execution time.
public:
CListOfNumbers();
~CListOfNumbers();
};
You are required to count the number of elements in list after performing each add or delete
operation on list.
class CListOfNumbers
{
private:
double Item[MaxItems];
int Size;
public:
int Count() const;
CListOfNumbers();
};
17
Department of Software Engineering/Computer Science
CListOfNumbers::CListOfNumbers()
{
Size = 0;
}
intCListOfNumbers::Count() const
{
return Size;
}
Creating a list, consists of adding elements to it. Elements are usually added one at a time and
easiest way to do this is to add an item at the end of the list.
To add an item to the list, you first need to test whether the list is already full or not. A list is full
if its count of items is equal to or higher than the maximum number you had set. If the list is not
empty, you can add an item at the end and increase the count by one. Following code segment
represent this functionality.
Item[size] = item;
size++;
return true;
}
return false;
}
After adding elements to a list, you can retrieve them to do what you intended the list for. To
retrieve an item, you can locate an item by its position. By using index of this array, you can
check if the position specified is negative or higher than the current total of elements. It means
index is out of range. If the index is in the right range, you can retrieve its item against that
index. Following code segment represents this functionality.
return 0;
}
18
Department of Software Engineering/Computer Science
Inserting a new item in the list allows you to add it at a position of you chooses. To insert a new
element in the list, you must provide the new item and the desired position. Before performing
this operation, you must first check two conditions. First, the list must not be empty. Second, the
specified position must be in the valid range. Following code segment provides implementation
of this method.
Item[pos] = item;
size++;
return true;
}
return false;
}
Another operation you may perform on a list consists of deleting an element. To delete an item
from the list, you need to provide its position in the list. Before performing the operation, you
can first check that the specified position is valid. Following code segment provides
implementation.
size--;
return true;
}
return false;
}
19
Department of Software Engineering/Computer Science
After studying the introduction and concept map sections you should be ready to provide
the solution of following problems. Design the solutions of the problems in C++ and
bring your code to lab so that lab instructor should access and grade it.
5.3.1 Task-1
Make a list of at least 5 benefits we may get while using dynamic lists.
5.3.2 Task-2
Provide comparison between implementation of lists using static and dynamic arrays.
6. Procedure& Tools
This section provides information about tools and programming procedures used for the lab.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
20
Department of Software Engineering/Computer Science
Operations related to list such as addition, removal, element count and element retrieval are
implemented in this program as well. Figure 3 shows some of these operations.
Figure 3: Insert operation on lists using arrays in Microsoft Visual Studio 2017
21
Department of Software Engineering/Computer Science
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
22
Department of Software Engineering/Computer Science
}
}
else
{
cout<<"Display: No items to be displayed. List is empty\n";
}
}
////////////////////////////////// List manipulation operations
// Insert after cursor
void insert (int newDataItem)
{
if(!isFull())
{
elements[length]=newDataItem;
length++;
}
else
{
cout<<"Insert: Cannot insert more items. List is full\n";
}
}
// Remove data item
int remove ()
{
if(!isEmpty())
{
length--;
return elements[length];
}
else
23
Department of Software Engineering/Computer Science
{
cout<<"Remove: Cannot remove the item. List is empty\n";
}
}
// Replace data item
void replace ( int newDataItem, int position )
{
//Condition: List contains at least position+1 data items.
//Result: Removes the data item present at the position from a list and replace the number
requested by user at its position.
if(length<position)
{
cout<<"Replace: Cannot replace the item. Invalid position requested\n";
}
else
{
//implement your logic here
}
}
// find any number
bool find ( int searchDataItem )
{
//Condition: List is not empty.
//Result: Check if the number is present in the list or not
if(!isEmpty())
{
for(int i=0;i<length;i++)
{
//implement your logic here
}
24
Department of Software Engineering/Computer Science
}
}
/////////////////////////////////////// List status operations
// check if List is empty
bool isEmpty ()
{
// implement your logic here
}
Create a list of Employees (List can be as long as user wants). Program should save the
following information for each Employee: Name, Emp. No., Experience, Designation and
Salary. Now perform the following tasks:
a) Your program should save the information of only those employees whose experience is
at least 2 years.
b) Display only those Employees whose Salary is greater than 50,000
c) Display the Employees alphabetically
25
Department of Software Engineering/Computer Science
7.5 Testing
Test Cases for Practice Task-1
Sample Input Sample Output
2
3
4
6
9
Delete an element from Element deleted
location: 3
Sample Sample
Inputs-1 Outputs-1
Input elements in list:
Bookno : B123
Title: C++ programming
Price: 234.95
Author: Jone Sage
Bookno: B345
Title: Object Oriented Programming in C++
Price: 235.95
Author: B J Shamy
Bookno: B133
Title: Data Structures using C and C++
Price: 400.35
26
Department of Software Engineering/Computer Science
Author: Dietel J.
Enter an index to place a in list: Book with bookno:
B133 is Placed at
7 location 7 in list
Please enter the information of book:
Bookno: B133
Title: Data Structures using C and C++
Price: 400.35
Author: Dietel J.
Enter an index to place a book in the list: Sorry the entered index
has already a book.
3
27
Department of Software Engineering/Computer Science
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
1. https://www.cplusplus.com/doc/tutorial/
28
Department of Software Engineering/Computer Science
29
Department of Software Engineering/Computer Science
1. Introduction
Objective of this lab is to introduce the implementation of stack in C++ and further introduce
concept of class templates and defining a stack as a class template or generic class. A stack
allows last in first out (LIFO) operations. We can place a new element at top of stack and we
may remove an element from top of stack. Stacks can be implemented using static as well as
dynamic arrays. Further we may implement a stack as a generic class/class template.
A stack can be implemented using a static array in C++. We need to define an array with a
maximum size and a variable of integer type normally called “top” for such stack. Stack is
initially set to empty when program is executed, so at start of program top is set to -1 which
represents an empty stack. There are two operations associated with a stack; push operation—
used to add an element at top of stack and pop operation – to remove an element from top of
stack. When push operation is performed we need to check that whether stack exceeds its
maximum size or not, this is called stack overflow condition check. When pop operation is
performed we need to test that whether stack is empty or not, this is called stack underflow
condition check.
30
Department of Software Engineering/Computer Science
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.
stack::stack()
31
Department of Software Engineering/Computer Science
{
tos = -1;
}
void stack::push(int x)
{
if(!full())
arr[++tos] = x;
else
cout<< "Stack is full, Cannot push " << x <<endl;
}
int stack::pop()
{
if(!empty())
return arr[tos--];
else
cout<< "Stack is empty, cannot pop" <<endl;
return -1;
}
bool stack::empty()
{
if(tos == -1)
return true;
else
return false;
}
bool stack::full()
{
if(tos+1 == STACKSIZE)
return true;
else
return false;
}
int stack::size()
{
return tos;
}
void stack::display()
{
if(tos == -1)
{
32
Department of Software Engineering/Computer Science
int main()
{
stackmystack;
cout<<mystack.size() <<endl;
mystack.push(1);
if(mystack.full())
cout<< "stack is full" <<endl;
mystack.pop();
if(mystack.empty())
cout<< "stack is empty" <<endl;
}
Following figure 1 represents the functionality of pop and push operations on a stack
implemented using a static array.
33
Department of Software Engineering/Computer Science
For the array implementation, we need to keep track of (at least) the array contents and a top
index. Definition of stack class will be as:
class Stack{
public:
Stack(int stack_size);
~Stack();
void push(int x);
int pop();
bool isEmpty();
bool isFull();
private:
char *contents;
int top;
};
Stack::Stack(int stack_size)
{
if (contents == NULL) {
cout<< "Insufficient memory to initialize stack.\n";
exit(1);
}
maxSize = stack_size;
top = -1;
}
Stack::~Stack()
{
delete [] contents;
contents = NULL;
maxSize = 0;
top = -1;
}
if (isFull()) {
cout<< "Can't push element on stack: stack is full.\n";
exit(1);
}
contents[++top] = element;
}
char Stack::pop()
{
if(!isEmpty())
return contents[--top];
else
cout<< "Stack is empty, cannot pop" <<endl;
return -1;
}
35
Department of Software Engineering/Computer Science
36
Department of Software Engineering/Computer Science
double d[] =
{1.0, 3.0, 5.0, 7.0, 9.0, 0.0};
int i = 0;
while (d[i] != 0.0 && !ds.full())
if (!ds.full()) ds.push(d[i++]);
while (!ds.empty())
cout<<ds.pop() << " ";
cout<<endl;
return 0;
}
6. Procedure& Tools
This section provides information about tools and programming procedures used for the lab.
37
Department of Software Engineering/Computer Science
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
We will discuss the demonstration of stack using static array in Microsoft Visual Studio 2017.
You are required to open an empty Win32 console application. You have already knowledge of
creating a console application in Microsoft Visual Studio 2017 in your courses: computer
programming and object oriented programming, which you have previously studied.
Figure 2: Stack definition using static array in Microsoft Visual Studio 2017
38
Department of Software Engineering/Computer Science
Figure 3: Implementation of push and pop operations for stack using static array in Microsoft
Visual Studio 2017
Figure 4: Output window displaying values from stack in Microsoft Visual Studio 2017
39
Department of Software Engineering/Computer Science
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
Create a Stack of integer using arrays. Give the following menu to the user and then implement
the given operations:
40
Department of Software Engineering/Computer Science
a) Find the Minimum number of bracket reversals needed to make an expression balanced.
A balanced expression is an expression in which all opening brackets have respective
closing brackets. For example 2+ {3*(7-2)} is a balanced expression whereas 2+{3*(7-
2}is not a balanced expression. Write a program to ask user to enter an expression.
Expression must consists of only brackets {or}, but the expression may not be balanced.
Find minimum number of bracket reversals to make the expression balanced.
b) Delete consecutive same characters in a sequence using stack. Ask user to enter a series
of characters until user enters ‘F’ or ‘f’. Now the task is to check if any two similar
characters come together then they destroy each other. Print the new sequence after this
pair wise destruction.
7.5 Testing
Sample Sample
Inputs-1 Outputs-1
Push elements for stack:
2
3
4
5
8
Enter number of elements to be popped
from stack1: 3
Elements of stack popped:
8
5
4
41
Department of Software Engineering/Computer Science
Sample Sample
Inputs-1 Outputs-1
Input : abaabcdabf
new sequence is:
acdab
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
42
Department of Software Engineering/Computer Science
1. http://www.slideshare.net/nita23arora/stacks-queues-presentation
43
Department of Software Engineering/Computer Science
44
Department of Software Engineering/Computer Science
Two key operations which are defined for queues are addQueue (enqueue) and deleteQueue
(dequeue). As elements cannot be deleted from an empty queue and cannot be added to a full
queue, therefore we need two more operations called IsEmptyQueue (to check whether a queue
is empty) and IsFullQueue (to check whether a queue is full). Another operation which is
required for queues is initializeQueue: to initialize a queue in empty state, it means it should not
contain any elements in it when queue is created. To retrieve the front and last elements of queue
we need to have two operations called front and last operations.
45
Department of Software Engineering/Computer Science
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.
Before writing the algorithms for queue operations, we need to decide that how queueFront and
queueRear will be used to access the queue elements. How queueFront and queueRear indicate
that status of queue that the queue is empty or full? If queueFront gives the index of the first
element of the queue and queueRear gives the index of the last element of the queue. To add an
element to the queue, first we advance queueRear to the next array position and then add the
element to the position that queueRear is pointing to. To delete an element from the queue, first
we retrieve the element that queueFront is pointing to and then advance queueFront to the next
element of the queue. It means queueFront will be changing after each deleteQueue operation
and queueRear will be changing after each addQueue operation.
Let us see what will happen when queueFront changes after a deleteQueue operation and
queueRear changes after an addQueue operation. Assume that size of array to holding queue
elements is 100.
46
Department of Software Engineering/Computer Science
An array for a queue is normally initialized by setting queueFront and queueRear to -1.
queueRear=-1; queueFront=-1;
When an element is required to be added in queue, we need to check that whether queue
overflow condition occurs or not, it means whether queue will exceed its maximum size on
addition of an element to queue or not? If x is an element to be inserted in a queue based on array
“Queue” with a maximum size MAX_QUEUE, then following code segment represents
implementation of addQueue or enqueue operation.
if(queueRear> MAX_QUEUE-1)
{ cout<<"queue over flow";
47
Department of Software Engineering/Computer Science
queueFront=queueRear=-1;
return; }
Queue[++queueRear]=x;
cout<<"inserted" <<x;
When an element is required to be remove from a queue, we need to check that whether queue is
empty or not, because we cannot remove an element from an empty queue. Following code
segment represents this operation.
if(queueFront==queueRear)
{ cout<<"queue under flow"; return; }
cout<<"deleted" <<Queue[++queueFront];
6 Procedure& Tools
This section provides information about tools and programming procedures used for the lab.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
In this task we will implement and test the evaluation of post fix expression and a program for a
queue using static array using C++.Figure 4 and 5 represents the source code view of queue
program in visual studio. You are required to type this code and further debug and execute the
program.
48
Department of Software Engineering/Computer Science
49
Department of Software Engineering/Computer Science
Following is output window of this program in figure 4 and figure 5, when executed.
7 Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
Partial solution of a Linear Queue Class is given below. Complete the missing code in the functions to
run the program properly.
Class Queue
int *elements;
int size;
////////////////////////////////// Constructor
50
Department of Software Engineering/Computer Science
size=maxsize;
elements=new int[size];
/////////////////////////////////// Destructor
~ Queue()
delete []elements;
void showStructure ()
if(!isEmpty())
for(int i=0;i<rear;i++)
cout<<"Element:"<<elements[i]<<endl;
else
// Insert in queue
if(!isFull())
if(front==-1)
{front=0;}
elements[rear]=newDataItem;
rear++;
51
Department of Software Engineering/Computer Science
else
void Dequeue ()
if(!isEmpty())
// delete a data item from front end and shift all the remaining items to fill the gap at the front.
else
// Clear queue
void clear ()
// Removes all the data items in a queue but the queue itself
bool isEmpty ()
bool isFull ()
};
52
Department of Software Engineering/Computer Science
Write a program to implement Parking area reservation. The parking area has only one way out
and one-way inn; so scheduling has to be done for the arrival and departure of vehicles in the
parking area. At one time, only one vehicle can arrive or leave the area. Scheduling has to be
done on the basis of first come, first serve. Whichever vehicle comes first at the parking area will
be given the space in the parking area. Similarly, whichever vehicle requests for departure first,
will be given the space to the exit.
[Hint: Arrival of vehicle=enqueue, Departure of vehicle=dequeue]
7.5 Testing
Test Cases for Practice Task-1
Sample Sample
Inputs-1 Outputs-1
Enter values to be inserted for
queue
2
3
4
7
8
Dequeue: 2
Dequeue: 3
Dequeue: 4
Values in queue: 7 8
53
Department of Software Engineering/Computer Science
54
Department of Software Engineering/Computer Science
Press 4 to Calculate the time required to serve all the remaining customers
Enter choice: 1
Enter customer name: Aliya
Press Y/y to continue: y
55
Department of Software Engineering/Computer Science
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 2: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7,8 Practice tasks and Testing 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10
56
Department of Software Engineering/Computer Science
57
Lab 5: Circular and Priority Queues
1. Introduction
This lab will introduce concept of circular and priority queues. In standard queues when
dequeue operation is performed a problem called de-bufferring occurs, to solve this problem we
need to use circular queues. Beside the circular queues we may also use priority queues, in such
queues we may delete an element from queue on the basis of some priority. In First in first out
queues, the element at start of queue has highest priority to be removed from queue.
Circular queuesare linear data structures. It follows FIFO (First In First Out) rule.
• In circular queue the last element is connected back to the first element to make a
circle.
• Elements are inserted at the rear end and the elements are removedfrom front end of
the queue.
• Both the front and the rear pointers point to the beginning of the array.
• It is also called as “Ring buffer”.
Priority queues are used in such situations where you want to remove an element from
queue which is not at the moment at front of queue, but its priority is high. For example in daily
life if in some hospital there is a queue of patients waiting for checkup/treatment from doctor. If
some patient comes whose have light threatening symptoms and need urgent treatment then he
should be at high priority in that queue and should be removed from queue on his priority, may
be patient at front of queue at the moment has come for general checkup.
58
Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Design Evaluation 20mins 20mins
6.2 Walk through tasks 20mins 20mins
7 Practice tasks 20mins for task 1, 25mins for 70mins
task 2 and 3.
9 Evaluation Task 60mins for all assigned tasks 60mins
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
Suppose we have given an array to implement a FIFO queue. We are using queueFront
and queueRear two elements referring indices of this array. Now if we perform addition and
removal of element on this array in such a way that after addition of three elements we remove
one element. On performing addition queueRear will move to index of next element of array.
When queueRear will point to last element of array after that it cannot use any other element of
array for insertion of further element in this array. Figure 1 shows this scenario.
So we may use this array in circular fashion so that rear can move to starting element
after reaching last element of array. Figure 2 represents the logical circular array which can be
used.
59
Figure 2: Logical representation of a circular array (Ring Buffer)
Because the array containing the queue is circular, we can use the following statement to
advance queueRear (queueFront) to the next array position:
queueRear = (queueRear + 1) % maxQueueSize;
If queueRear<maxQueueSize - 1,
ThenqueueRear + 1 <= maxQueueSize - 1,
so(queueRear + 1) % maxQueueSize = queueRear + 1.
IfqueueRear == maxQueueSize- 1
(That is, queueRear points to the last array position),
queueRear + 1 ==maxQueueSize,
So (queueRear + 1) % maxQueueSize = 0. In this case, queueRear will be set to 0, which
is the first array position.
struct data
{
char job[MAX];
int prno ;
int ord ;
};
struct pque
{
data d[MAX];
int front ;
int rear ;
};
60
Following function is used to initialize the queue attributes.
pq -> rear++ ;
pq -> d[pq -> rear] = dt ;
if ( pq -> front == -1 )
pq -> front = 0 ;
61
if ( pq -> d[i].prno == pq -> d[j].prno )
{
if ( pq -> d[i].ord>pq -> d[j].ord )
{
temp = pq -> d[i] ;
pq -> d[i] = pq -> d[j] ;
pq -> d[j] = temp ;
}
}
}
}
}
}
if ( pq -> front == -1 )
{
cout<<"\nQueue is Empty."<<endl;
return t ;
}
62
pq -> front++ ;
return t ;}
After studying the introduction and concept map sections you should be ready to provide the
solution of following problems. Design the solutions of the problems in C++ and bring your code
to lab so that lab instructor should assess and grade it.
Write a program to implement a priority queue to store the objects of “person” class. “person”
class should contain attributes (privately defined) per_ssn (string), per_name (string), per_age
(int) and per_priority(int). “person” class should also contain member functions (publicly
defined); constructor, input and output functions. You are required to design a priority queue
class which should use static array implementation. Your queue class should contain constructor,
destructor (if required), enqueue, dequeue, displayElements operations and conditions to check
empty or full queue. The member function dequeue should remove an object of person class
which should have high priority number than that of object at front of queue.
6. Procedure& Tools
This section provides information about tools and programming procedures used for the
lab.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
63
6.2 Walk through Tasks [Expected time = 20mins]
By using Microsoft Visual Studio 2017, we can implement a program for a priority queue
using static array. Following figure 3 represent the source code view of this program in visual
studio. You are required to type this code and further debug and execute the program.
64
Figure 4: Implementation of a priority queue
65
Figure 6 shows output of program in figure 3, figure 4 and figure 5.
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and placesolution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
66
elements which have been removed from circular queue. Implement the task using template
class.
After completing this lab, student will be able to understand and develop programs related to
circular and priority queues using static arrays in C++ using Microsoft Visual Studio 2017
environment.
7.5 Testing
Test Cases for Practice Task-1
Sample Input Sample Output
Insert elements in rear of circular
queue:
2
3
4
5
7
8
6
9
11
1
Enter number of elements to be 2
removed from circular queue: 4
3
4
5
Average of removed values is: 3.5
67
Test Cases for Practice Task-2
Sample input/output:
Press 1 to enter Information
Press 2 to call for interview
Press 3 to view all Candidates
Enter choice: 1
Enter Name: Ali
Enter CNIC: XXXXX-XXXXXXX-X
Enter Qualification: MS
Enter Experience: 4
Enter Your Marks in Written Test: 35
68
Enter Qualification: BS
Enter Experience: 4
Enter Your Marks in Written Test: 40
Sample input/output:
69
Press 1 to enter Information
Press 2 to call for bill Payment
Press 3 to view all persons
Enter choice: 1
Enter your Name: Firdous
Enter your CNIC: XXXXX-XXXXXXX-X
Enter your Age: 35
70
Ahmed Ali please come for billpayment.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
71
Lab Manual for Data Structures
Lab 6
Linked List Implementation
72
Lab 6: Linked List Implementation
1. Introduction
This lab will introduce concept of dynamic memory based data structures such as linked
lists. In case of some real world applications we don’t know about the storage requirements of
program before program execution, in that scenario dynamic data storage systems are useful. We
will learn about linear linked list structure and how linked lists are helpful to store data during
program execution.
A linked list is a collection of elements, called nodes. Every node (except the last node)
stores the address of the next node. Therefore, every node in a linked list has two components:
one to store the data and other to store the address, called the link, of the next node in the list.
The address of the first node in the list is stored in a separate location, called the head or first.
Linked list: A list of elements, called nodes, in which the order of the nodes is determined by the
address, called the link, stored in each node.
We may perform different operations on linked lists such as inserting a node, deleting a node,
traversing a linked list etc.
73
2. Activity Time boxing
• To understand and implement linear linked lists with their operations in C++.
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
Node of a linked list is a self-referential structure which can be represented by following code.
Struct nodeType
{
int info;
nodeType *link;
};
The basic operations of a linked list are as follows: Search the list to find out whether aparticular
item is in the list, insert an item in the list, and delete an item from the list.These operations
require the list to be traversed. That is, given a pointer to the first nodeof the list, we must step
through the nodes of the list. Following code segment helps in traversal.
74
current = head;
while (current != NULL)
{
//Process current
current = current->link;
}
This section discusses how to insert an item into, and delete an item from, a linked list.Consider
the following definition of a node. (For simplicity, we assume that the infotype is int.)
struct nodeType
{
int info;
nodeType *link;
};
Suppose that p points to the node with info 65, and a new node with info 50 is to becreated and
inserted after p. Consider the following statements:
To delete a node from linked list we can use following code segment.
75
q = p->link;
p->link = q->link;
delete q;
After studying the introduction and concept map sections you should be ready to provide
the solution of following problems. Design the solutions of the problems in C++ and
bring your code to lab so that lab instructor should assess and grade it.
Write a program of linear linked list of objects of “person” class. Attributes of “person”
class (privately defined) are per_id (int), per_name (string) and per_age (int). “person”
class contains member functions (publicly defined): constructor, input and output
functions. You are required to define a class for linear linked list. This class should
contain the member functions to insert, delete nodes from linear linked list. This class
should also contain the member functions to display values of all nodes of linear linked
list.
6. Procedure& Tools
This section provides information about tools and programming procedures used for the
lab.
76
6.1 Tools
Following screens in figure 5 to 13represent source code implementation of a linear linked list
class in Microsoft Visual Studio 2017. You are required to type, debug and execute this program
in Microsoft Visual Studio 2017.
This linked list program provides different functions like addition of node at start of list,
deletion of node from list, displaying elements of list, addition of node at end of list, add a node
after some specific node in the list.
77
Figure 6: Implementation of linear linked list class in Visual Studio 2017
78
Figure 8: Implementation of linear linked list class in Visual Studio 2017
79
Figure 10: Implementation of linear linked list class in Visual Studio 2017
Figure 11: Implementation of linear linked list class in Visual Studio 201
80
Figure 12: Implementation of linear linked list class in Visual Studio 2017
Figure 13: Implementation of linear linked list class in Visual Studio 2017
81
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and placesolution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
7.5 Testing
82
Test Cases for Practice Task-1
Sample Input Sample Output
Enter the values of elements of
linked list:
2
3
4
5
7
8
6
9
11
1
Enter the value after which you New value inserted after 11
want to insert: 11
Enter the value to delete from Key value 5 is deleted from linked
linked list: 5 list.
Sample input/output:
Press 1 to add Book
Press 2 to delete Books having price more than 2000
Press 3 to display list
Enter choice:1
Enter Title: The Art of Computer Programming
83
Enter Authors: Donald Knuth
Enter Edition: 3
Enter Price: 1500
Press Y/y to continue: y
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
85
10. Further Readings
86
\
87
Lab7: Linked Lists as Stack and Queue
1. Introduction
Objective of this lab is to make you understand the usage of linked list structure for
implementation of stack and queue ADT (Abstract Data Types). If we need to maintain a stack
whose individual elements are allocated memory space during program execution, we need to
use linked list for that purpose, same is case for queue. In case of array based stacks and queues
we may only store finite number of elements which will be limited to maximum size of array.
Stack can be implemented by linked lists structure. In this case we need to maintain a
pointer to node of linked list which always point to a node before the top of stack, when an
element is inserted in list it is placed at top of stack and when an element is removed it is also
removed from top of stack. In this way stacks can be used by linked list structures. As memory
of elements of stack is dynamically allocated so stack will never be filled (we don’t need to
check for stack overflow conditions). Figure 1 provides information about the use of stack as a
linked list structure.
Because the size of the array to stock up the queue elements is fixed, only a finite number
of queue elements can be stored in the array. Also, the array implementation of the queue
requires the array to be handled in a special way together with the values of the indices
queueFront and queueRear. The linked list implementation of a queue simplifies many of the
special cases of the array implementation and, because the memory to store a queue element is
allocated dynamically, the queue is never full. It means we don’t need to check for queue
overflow condition, we need to maintain only queue underflow condition that is we need to
check whether queue is empty or not while removing an element from the queue.
1.3. Relevant Lecture Readings
88
ii. Revise Lecture No. 23 and 24 available at \\dataserver\jinnah$\ in instructor’s
folder.
iii. From books: C++ Data Structures by Nell Dale (Page280 - 317) and Data structures
using C++ by D. S. Malik (Page415 - 423).
• To understand and implement stacks using linked lists with their operations in C++.
• To understand and implement queues using linked lists with their operations in C++.
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
The first operation that isto be considered is the default constructor. The default constructor
initializes the stack to an empty state when an object of stack class is declared. Thus, this
function sets stackTop pointer to NULL. The definition of this function is as follows:
template<class Type>
linkedStackType<Type>::linkedStackType()
{
stackTop = NULL;
}
89
The operations isEmptyStack and isFullStack are easy to understand. The stack is empty if
stackTop is NULL. Also, because the memory for elements of stack is allocated and deallocated
dynamically, the stack is never full. Thus, the function isFullStack always returns the value false.
The definitions of the functions to implement these operations are asfollows:
template<class Type>
bool linkedStackType<Type>::isEmptyStack() const
{
return(stackTop == NULL);
} //end isEmptyStack
template<class Type>
bool linkedStackType<Type>::isFullStack() const
{
return false;
} //end isFullStack
template<class Type>
void linkedStackType<Type>::push(const Type &newElement)
{
nodeType<Type> *newNode; //pointer to create the new node
newNode = new nodeType<Type>; //create the node
newNode->info = newElement; //store newElement in the node
newNode->link = stackTop; //insert newNode before stackTop
stackTop = newNode; //set stackTop to point to the
//top node
} //end push
90
Pop operation for stack can be defined by following code segment.
template<class Type>
void linkedStackType<Type>::pop()
{
nodeType<Type> *temp; //pointer to deallocate memory
if(stackTop != NULL)
{
temp = stackTop; //set temp to point to the top node
stackTop = stackTop->link; //advance stackTop to the
//next node
delete temp; //delete the top node
}
else
cout<< "Cannot remove from an empty stack." <<endl;
}//end pop
Some operations related to implementation of queue as a linked list are provided in this
section. The queue is empty if queueFront pointer is NULL. Memory to store the queue elements
is allocated dynamically. Therefore, the queue is never full and so the function to implement the
isFullQueue operation returns the value false. Implementation of functions for checking empty or
full queue is given below:
template<class Type>
boollinkedQueueType<Type>::isEmptyQueue() const
{
return(queueFront == NULL);
} //end
template<class Type>
91
bool linkedQueueType<Type>::isFullQueue() const
{
return false;
} //end isFullQueue
The addQueue operation inserts a new element at the rear of the queue. To implement this
operation, we will use the pointer queueRear. If the queue is non-empty, the operation front
returns the first element of the queue and therefore the element of the queue indicated by the
pointer queueFront is returned. If thequeue is empty, the function front stops execution of
program. If the queue is nonempty, the operation back returns the last element of the queue and
so the element of the queue indicated by the pointer queueRear is returned. If the queue isempty,
the function back stops the execution of program. Similarly, if the queue is nonempty, the
operation deleteQueue removes the first element of the queue, and so we access the pointer
queueFront for this purpose. The definitions of the functions to implement these operations are
as follows:
template<class Type>
void linkedQueueType<Type>::addQueue(const Type&newElement)
{
nodeType<Type> *newNode;
newNode = new nodeType<Type>; //create the node
newNode->info = newElement; //store the info
newNode->link = NULL; //initialize the link field to NULL
if (queueFront == NULL) //if initially the queue is empty
{
queueFront = newNode;
queueRear = newNode;
}
else //add newNode at the end
{
queueRear->link = newNode;
92
queueRear = queueRear->link;
}
}//end addQueue
template<class Type>
Type linkedQueueType<Type>::front() const
{
assert(queueFront != NULL);
return queueFront->info;
} //end front
template<class Type>
Type linkedQueueType<Type>::back() const
{
assert(queueRear!= NULL);
return queueRear->info;
} //end back
template<class Type>
void linkedQueueType<Type>::deleteQueue()
{
nodeType<Type> *temp;
if (!isEmptyQueue())
{
temp = queueFront; //make temp point to the first node
queueFront = queueFront->link; //advance queueFront
delete temp; //delete the first node
if (queueFront == NULL) //if after deletion the
93
//queue is empty
queueRear = NULL; //set queueRear to NULL
}
else
cout<< "Cannot remove from an empty queue" <<endl;
}//end deleteQueue
After studying the introduction and concept map sections you should be ready to provide
the solution of following problems. Design the solutions of the problems in C++ and
bring your code to lab so that lab instructor should assess and grade it.
Write a program of linear linked list to implement a stack and a queue of objects of
“person” class. Attributes of “person” class (privately defined) are per_id (int), per_name
(string) and per_age (int). “person” class contains member functions (publicly defined):
constructor, input and output functions. You are required to define two more classes: one
of these classes should define the linked list implementation of stack for objects of
“person” class, this class should contain member functions like push, pop, display and to
check whether stack is empty or not? Other class should define the linked list
implementation of queue for objects of “person” class, this class should contain the
member functions like addQueue, RemoveQueue, display and check whether the queue is
empty or not?
94
6. Procedure& Tools
This section provides information about tools and programming procedures used for the
lab.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
This linked list implementation of stack program provides functionality to use a stack. It
contains a structure to represent the nodes of linked list and a class named “stack” which will be
representing the stack as linked list. This class contains constructor, push, pop and display
member functions. In main function we create an object of stack class and call member functions
of class to push and pop elements from the stack.
95
Figure 3: Implementation of stack as a linked list.
96
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and placesolution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
After completing this lab, student will be able to understand and develop programs related to
linked list implementation of stacks and queuesin C++ using Microsoft Visual Studio 2017
environment.
7.4 Testing
Test Cases for Practice Task-1
Sample Input Sample Output
Enter a string:
Evil olive
Entered string is palindrome
Enter a string:
Computer
Entered string is not palindrome
97
Enter order details:
Customer name: Ali
Items:4
Total cost:10000
98
Items:7
Total cost:25000
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
2. http://stackoverflow.com/questions/3600245/fifo-queue-linked-list-implementation
99
Lab Manual for Data Structures
Lab 8
Doubly Linked List and DECK Implementations
100
Lab 8: Doubly Linked List and DECK Implementations
1. Introduction
This lab will introduce concept of dynamic memory based data structures such as linked
lists. In case of some real world applications we don’t know about the storage requirements of
program before program execution, in that scenario dynamic data storage systems are useful. We
will learn about linear, circular and doubly linked list structures and how linked lists are helpful
to store data during program execution.
A doubly linked list is a linked list in which every node has a next pointer and a back
pointer. In other words, every node contains the address of the next node (except the last node),
and every node contains the address of the previous node (except the first node). See Figure 4.
101
3. Objectives of the experiment
• To understand and implement linear linked lists with their operations in C++.
• To understand and implement circular linked lists with their operations in C++.
• To understand and implement doubly linked lists with their operations in C++.
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
102
}
else
{
found = false;
current = first;
while (current != NULL && !found) //search the list
if (current->info >= insertItem)
found = true;
else
{
trailCurrent = current;
current = current->next;
}
if (current == first) //insert newNode before first
{
first->back = newNode;
newNode->next = first;
first = newNode;
count++;
}
else
{
//insert newNode between trailCurrent and current
if (current != NULL)
{
trailCurrent->next = newNode;
newNode->back = trailCurrent;
newNode->next = current;
current->back = newNode;
103
}
else
{
trailCurrent->next = newNode;
newNode->back = trailCurrent;
last = newNode;
}
count++;
}}}//end insert
To delete a node from a doubly linked list, following cases should be considered:
104
first = first->next;
if (first!= NULL)
first->back = NULL;
else
last = NULL;
count--;
delete current;
}
else
{
found = false;
current = first;
while (current != NULL && !found) //search the list
if (current->info >= deleteItem)
found = true;
else
current = current->next;
if (current == NULL)
cout << "The item to be deleted is not in "
<< "the list." << endl;
else if (current->info == deleteItem) //check for equality
{
trailCurrent = current->back;
trailCurrent->next = current->next;
if (current->next != NULL)
current->next->back = trailCurrent;
if (current == last)
last = trailCurrent;
count--;
105
delete current;
}
else cout << "The item to be deleted is not in list." <<endl;}
On the other hand, a doubly linked list is a concrete data structure, i.e. its implementation would
be same for every programmer. It is a way for storing data.
After studying the introduction and concept map sections you should be ready to provide
the solution of following problems. Design the solutions of the problems in C++ and
bring your code to lab so that lab instructor should assess and grade it.
106
5.3 Practices from home
5.3.1 Task-1
Compare linear linked list with doubly linked list and provide three differences between
the two structures.
5.3.2 Task-2
List three real world examples in which doubly linked list structures can be used.
6.1 Tools
This linked list program provides different functions like addition of node at start of list,
deletion of node from list, displaying elements of list.
107
Figure 6: Implementation of doubly linked list
108
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
Write a program which should implement All four cases as mentioned in section 4.2.
After completing this lab, student will be able to understand and develop programs related to
linear linked lists, circular linked lists and doubly linked lists in C++ using Microsoft Visual
Studio 2017 environment.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
109
Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7,8 Practice tasks 35
4 8.1 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10
10.Further Readings
10.1 Web sites related to C++ tutorials about linked lists
1. http://www.cprogramming.com/tutorial/lesson15.html
2. http://www.element14.com/community/community/code_exchange/blog/2013/03/26/
c-tutorial--linked-list
110
Lab Manual for Data Structures
Lab-9
Recursion in C++
111
Lab9: Recursion in C++
1. Introduction
Objective of this lab is to provide you knowledge about recursion in C++. You have
come to know about the basic concepts about C++ language in courses: computer programming
and object oriented programming. You have learned about the statements used in this language
like input/output statements, selection statements (if..else, switch) and iterative statements/loops
(while, do..while, for). Further you will also have knowledge about classes, encapsulation,
inheritance and polymorphism.
A program is a set of instructions that processes data which is given as input to it. If we
need to develop a good (efficient) program, we need to organize data in computer’s memory in
effective way. This organized data is called a Data Structure.
Study of computer science includes the study of how data (information) is organized in
computer and how it can be manipulated and utilized by programs. It is extremely important for
you to understand the concepts of data (information) organization and manipulation. Data
structures for storing information are lists, stacks, queues, trees, graphs and tables.
The process in which a function calls itself is known as recursion and the corresponding
function is called the recursive function. In recursion function there is a base condition which is
very important; without this base condition the function cannot execute properly. The purpose of
recursion is to divide the problem into smaller problems till the base condition is reached.
112
1.2.2 Indirect recursion:
When function calls another function and that function calls the calling function, then this is
called indirect recursion. For example: function A calls function B and Function B calls function
A.
a) From books: C++ Data Structures by Nell Dale (Page79-85) and Data structures using
C++ by D. S. Malik (Page130-135).
b) From books: C++ Data Structures by Nell Dale (Page 99-102) and Data structures
using C++ by D. S. Malik (Page 138-145).
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
113
4.2 Implementation of Recursion function in C++
A function that calls itself is known as recursive function. And, this technique is known as
recursion.
114
The recursion continues until some condition is met.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call and other doesn't.
4.3 Example
115
5 Homework before Lab
This homework will help students to study the concepts of topic before start of lab.
116
5.2 Problem description:
Design a program which should contain a recursive function for calculating sum of all
natural numbers up to a number given by user.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
6.2 Editing, Compiling and Running programs in Visual Studio 2017 [Expected
time = 5mins]
You are required to use Microsoft Visual Studio 2017 environment for programming on
data structures. It is expected that you are already familiar with this environment in your courses
of Computer Programming and Object Oriented Programming. You should be able to write code
in source code files (cpp files) and perform compilation of code. Beside that you are also
required to be proficient in performing line by line debugging and break point based debugging
to remove the errors from your code.
Following program represents the concept related to static and dynamic arrays; you are
required to type this program in editor of Visual Studio 2017, compile and run to see the output
of this program. Figure 3 shows the source code window of this program in Visual Studio 2017.
117
Figure 3: A program about recursion function in Visual Studio 2017.
Output of this program is shown in figure 4, when program is compiled and executed.
118
7 Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
Sample output:
Entered sequence of characters is palindrome.
After completing this lab, student will be able to understand and develop programs related to
static and dynamic arrays in C++ using Microsoft Visual Studio 2017 environment.
119
8. Evaluation Task (Unseen) [Expected time = 60mins for two
tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
Table 2: Evaluation of the Lab
Sr. No. Task No Description Marks
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10
120
Lab Manual for Data Structures
Lab 10
Binary Search Trees using Linked List and their Traversals
121
Lab 10: Binary Search Trees using Linked List and their
Traversals
1. Introduction
In this lab, we will discuss the usage of binary trees and binary search trees using linked
list notations. We will see that how we may insert and remove nodes from binary trees and how
pre order, post order and in order traversal can be performed on binary trees. We will further see
that how search operation can be performed on binary search trees which are stored using a
linked list notation.
A binary tree is used for storing and retrieving data rapidly. A binary tree is composed of
a parent node and child nodes which are connected with parent node and this structure may be
further repeated as required in tree. Binary trees can be represented using linked list structures.
Figure 1 represents the linked list structure of a binary tree. Each node
Binary search tree is sorted or ordered binary search tree, for which search operations can
be performed effectively. The left sub tree contains the nodes with keys less than that of root
node key and right sub tree contains nodes with keys greater than that of root node key. Both left
and right sub trees must be binary search trees. Binary search trees can also be represented using
linked list structure. Each node in tree is connected with other node using pointer variables. Each
node contains two pointers called left and right pointers. A leaf node contains left and right
pointers which are NULL. Left pointer of root node points to left sub tree and right pointer of
root node points to right sub tree.
122
1.3 Traversals in Binary Tree
When we need to insert, update or lookup items in a binary tree we need to perform
traversal of tree. Traversal of a binary tree means visiting each node of binary tree. Traversal
must start from the root node, for each node we have two options to traverse
These choices lead to three different traversals of a binary tree—in order, preorder, and post
order.
Pre order Traversal: In a pre-order traversal, the binary tree is traversed as follows:
Post order Traversal: In a post order traversal, the binary tree is traversed as follows:
For a binary tree shown in figure 2 following are results of pre order, in order and post
order traversals.
123
In order sequence: B D A C
Pre order sequence: A B D C
Post order sequence: D B C A
• To understand and implement binary trees using linked lists with their operations in C++.
• To understand and implement binary search trees using linked lists in C++.
• To understand and implement pre order, post order and in order traversals on binary trees
and binary search trees using recursive functions in C++.
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.
Insertion in BST
o Insertion begins as a search.
o Compare the key with root. If not equal search the left or right sub tree
o When a leaf node is reached add the new node to left or right based on the value.
Deletion in BST
o There are three possible cases to consider:
o Deleting a leaf (node with no children): Deleting a leaf is easy, as we can simply
remove it from the tree.
o Deleting a node with one child: Remove the node and replace it with its child.
o Deleting a node with two children: Call the node to be deleted N. Do not delete N.
Instead, choose either its in-order successor node or its in-order predecessor node,
R. Replace the value of N with the value of R, and then delete R.
#include <iostream>
using namespace std;
class Node {
int key;
Node* left;
Node* right;
Node* parent;
public:
Node() { key=-1; left=NULL; right=NULL; parent = NULL;};
void setKey(int aKey) { key = aKey; };
void setLeft(Node* aLeft) { left = aLeft; };
void setRight(Node* aRight) { right = aRight; };
void setParent(Node* aParent) { parent = aParent; };
int Key() { return key; };
125
Node* Left() { return left; };
Node* Right() { return right; };
Node* Parent() { return parent; };
};
class Tree {
Node* root;
public:
Tree();
~Tree();
Node* Root() { return root; };
void addNode(int key);
Node* findNode(int key, Node* parent);
void walk(Node* node);
void deleteNode(int key);
Node* min(Node* node);
Node* max(Node* node);
Node* successor(int key, Node* parent);
Node* predecessor(int key, Node* parent);
private:
void addNode(int key, Node* leaf);
void freeNode(Node* leaf);
};
There are three types of traversal of binary trees. Post order, in order and pre order
traversals. We will discuss code segments to be used for traversal of a binary tree which is
represented by an array.
126
Algorithm Preorder(Tree[1:N], root)
* Tree is the array holding the tree
* root is the subscript of the root node
* The empty positions in an array are denoted by -1
1. Print Tree[root]
2. if(Tree[2*root] ≠ -1) // Does a left child exist
3. call Preorder(Tree[], 2 * root)
4. end if
5. if ( Tree[2*root+1] ≠ -1) // Does a right child exist
6. call Preorder(Tree[], 2 * root+1)
7. end if
8. end Preorder
127
In Order Traversal:
Algorithm Inorder(Tree[1:N], root)
* Tree is the array holding the tree
* root is the subscript of the root node
* The empty positions in an array are denoted by -1
128
5.3 Practices from home
5.3.1 Task-1
Provide differences between binary tree and binary search tree implementations using
linked list structures.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
129
Figure 2: Binary search tree using linked list implementation.
130
Figure 4: Binary search tree using linked list implementation.
131
Figure 6: Binary search tree using linked list implementation.
132
Figure 8: Binary search tree using linked list implementation.
133
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
7.5 Testing
Test Cases for Practice Task-1
134
Post order: 1.5 1.9 2.1 5.6 3.4 2.3
In order: 1.5 1.9 2.1 2.3 3.4 5.6
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
135
Lab Manual for Data Structures
Lab 11
Binary Search Trees Iterative Traversals
136
Lab 11: Binary Search Trees Iterative Traversals
1. Introduction
This lab will introduce concept of generic binary trees, how they can be used to store
information. Further this lab will provide information about concept of performing different
traversal operations like pre order, in order and post order on binary trees.
When we need to insert, update or lookup items in a binary tree we need to perform
traversal of tree. Traversal of a binary tree means visiting each node of binary tree. Traversal
must start from the root node, for each node we have two options to traverse
These choices lead to three different traversals of a binary tree—inorder, preorder, and post
order.
Pre order Traversal: In a pre-order traversal, the binary tree is traversed as follows:
Post order Traversal: In a post order traversal, the binary tree is traversed as follows:
For a binary tree shown in figure 2 following are results of pre order, in order and post
order traversals.
138
Figure 2: A binary tree for traversal
In order sequence: B D A C
Pre order sequence: A B D C
Post order sequence: D B C A
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
139
4.1 Binary Tree Traversals
There are three types of traversal of binary trees. Post order, in order and pre order
traversals. We will discuss code segments to be used for traversal of a binary tree which is
represented by an array.
After studying the introduction and concept map sections you should be ready to provide
the solution of following problems. Design the solutions of the problems in C++ and
bring your code to lab so that lab instructor should assess and grade it.
140
5.2 Problem description:
Write a program of general binary tree using array. Elements of this array will be objects
of person class. Attributes of Book (privately defined) are
1. ISBN (String) (e.g. 1235-123-1)
2. author_name (string)
3. Edition (int)
Book class contains member functions (publicly defined): constructor, input and output
functions. You are required to define insert, delete and search functions for this binary
tree. Insert function should allow insertion of object of book class at appropriate location
in general binary tree, delete should delete an object of book class from tree whose ISBN
is specified by user. Search function should search an object of book class from this tree
whose ISBN is specified by user. You are required to implement pre order, in order and
post order traversal functions for this binary tree.
5.3.1 Task-1
Distinguish between recursive and iterative traversal in binary trees.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
141
Post Order Iterative Traversal implementation:
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
142
trees. Now pass the objects to a function which will display the intersection (common nodes) of
two trees. Note: Function must be iterative.
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
143
Lab Manual for Data Structures
Lab 12
AVL Trees
144
Lab 12: AVL Trees and Heaps
1. Introduction
In this lab, we will discuss the usage of AVL (Adelson-Velskii and Landis' tree) and heap
data structures. AVL trees are called self-balancing binary search trees. We will see how to
perform insert, remove and search operations on AVL trees.
An AVL tree (Adelson-Velskii and Landis' tree, named after the inventors) is a self-
balancing binary search tree. In an AVL tree, the heights of the two child sub trees of any node
are different by at most one; if at any time they be at variance by more than one, rebalancing is
done to restore this property. Lookup, insertion, and deletion all take O(log n) time in both the
average and worst cases, where n is the number of nodes in the tree proceeding to the operation.
Insertions and deletions may require the tree to be rebalanced by one or more tree rotations.
145
Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Design Evaluation 20mins 20mins
6.2 Walk through tasks 20mins 20mins
7 Practice tasks 30 mins for task 1, 20min for 80mins
task 2 and 30 mins for task 3
9 Evaluation Task 60mins for all assigned tasks 50mins
4. Concept Map
This concept map will help students to understand the main concepts of topic covered in
lab.
An AVL tree is a binary tree in which the dissimilarity between the height of the right and left
sub trees (or the root node) is never more than one.
#include <iostream>
using namespace std;
struct AVLTreeNode
{
int key;
// Other data fields can be inserted here
AVLTreeNode *left;
146
AVLTreeNode *right;
AVLTreeNode *parent;
char balanceFactor;
};
class Code203_Tree
{
private:
AVLTreeNode *root;
public:
Code203_Tree(); // Constructor
~Code203_Tree(); // Destructor
void Insert(AVLTreeNode *n);
void restoreAVL(AVLTreeNode *ancestor, AVLTreeNode *newNode);
void adjustBalanceFactors(AVLTreeNode *end, AVLTreeNode *start);
void rotateLeft(AVLTreeNode *n);
void rotateRight(AVLTreeNode *n);
void adjustLeftRight(AVLTreeNode *end, AVLTreeNode *start);
void adjustRightLeft(AVLTreeNode *end, AVLTreeNode *start);
// void Delete(int key); // Not implemented yet
void PrintTree();
private:
void ClearTree(AVLTreeNode *n);
void Print(AVLTreeNode *n);
};
#endif
147
5. Homework before Lab
This homework will help students to study the concepts of topic before start of lab.
5.3.1 Task-1
Compare AVL (self balancing) trees and balanced binary trees and find at least three
differences between these two implementations.
5.3.2 Task-2
Provide algorithmic representation of rotate function for AVL tree.
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
Following screens in figure 2 to 6 represent the implementation of AVL tree. You are
required to code and execute this program in Microsoft Visual Studio 2017.
148
Figure 2: Implementation of AVL tree.
149
Figure 4: Implementation of AVL tree.
150
Figure 5: Implementation of AVL tree.
151
Figure 6: Implementation of AVL tree.
7. Practice Tasks
This section will provide information about the practice tasks which are required to be performed
in lab session. Design solutions of problems discussed in each task and place solution code in a
folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
Modify Task 1 and add a delete function in it. User will enter a number your function should first
search that number and then it should delete the number from the tree. The tree must remain
balanced after deletion.
Write a program which should implement an AVL tree using linked list. Elements of tree are
objects of “student” class. “student” class contains attributes (privately defined) reg_no(int),
st_name (string) and cgpa (float). “student” class should also contain member functions
(publically defined); constructor, input and output functions. User will insert objects of class
“student” in AVL tree, values of attributes of objects will be provided by user. Program should
display the objects of student class in pre order, post order and in order traversal formats.
Program should also search an object from tree which is provided by user as input.
After completing this lab, student will be able to understand and develop programs related to
AVL trees and heap trees in C++ using Microsoft Visual Studio 2017 environment.
7.5 Testing
153
Test Cases for Practice Task-3
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab whether
the student has finished the complete/partial task(s).
154
10. Further Readings
10.1 Web sites related to C++ tutorials about AVL and Heap trees
1. http://www.cs.uah.edu/~rcoleman/Common/CodeVault/Code/Code203_Tree.html
2. http://www.cplusplus.com/reference/algorithm/make_heap/
155
Lab Manual for Data Structures
Lab 13
Heaps
156
Lab 13: Heaps
1. Introduction
In this lab, we will discuss the usage of heap data structures. Students will be able to
grasp the concept of heap trees. We will discuss the different operations to be performed on
heap trees.
In computer science, a heap is a particular tree-based data structure that satisfies the
heap property: If A is a parent node of B then key (A) is ordered with respect to key (B) with
the same ordering apply across the heap. Either the keys of parent nodes are always greater
than or equal to those of the children and the highest key is in the root node (this kind of heap
is called max heap) or the keys of parent nodes are less than or equal to those of the children
and the lowest key is in the root node (min heap). Heaps are critical in several efficient graph
algorithms such as Dijkstra's algorithm, and in the sorting algorithm heap sort.
Note that there is no implied ordering between siblings or cousins and no implied sequence for
an in-order traversal (as there would be in, e.g., a binary search tree). The heap relation
mention above applies only between nodes and their immediate parents. The maximum number
of children each node can have depends on the type of heap, but in many types it is at most
two, which is known as a "binary heap". Figure 2 represents a complete binary max heap tree.
157
2. Activity Time boxing
Table 1: Activity Time Boxing
Task Activity Name Activity time Total Time
No.
5.1 Design Evaluation 20mins 20mins
6.2 Walk through tasks 20mins 30mins
7 Practice tasks 30 mins for task 1 and 30 60mins
mins for task 2
9 Evaluation Task 60mins for all assigned tasks 60mins
4. Concept Map
This concept map will help students to understand the main concepts of topic covered
in lab.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
class Heap {
public:
Heap();
158
~Heap();
void insert(int element);
int deletemin();
void print();
int size() { return heap.size(); }
private:
int left(int parent);
int right(int parent);
int parent(int child);
void heapifyup(int index);
void heapifydown(int index);
private:
vector<int> heap;
};
6.1 Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.
159
6.2 Walk through Tasks [Expected time = 20 mins]
Following screens in figure 2 to 5 represent the implementation of a heap tree. You are
required to code and execute this program in Microsoft Visual Studio 2017.
160
Figure 4: Implementation of a heap tree.
161
Figure 5: Implementation of a heap tree.
7. Practice Tasks
This section will provide information about the practice tasks which are required to be
performed in lab session. Design solutions of problems discussed in each task and place
solution code in a folder specified by your lab instructor.
Lab instructors are guided to help students learn how ACM problems work and provide
students with certain practice/home tasks on the pattern of ACM Problems.
After completing this lab, student will be able to understand and develop programs related to
and heap trees in C++ using Microsoft Visual Studio 2017 environment.
7.4 Testing
Test Cases for Practice Task-1
Sample Input Sample Output
Enter the values of elements for
max heap tree:
2.3
3.4
1.5
5.6
2.1
1.9
Enter a value to exist in tree: 2.1 Value found in tree
162
8. Evaluation Task (Unseen) [Expected time = 60 mins for two tasks]
The lab instructor will give you unseen task depending upon the progress of the class.
9. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each
task is assigned the marks percentage which will be evaluated by the instructor in the lab
whether the student has finished the complete/partial task(s).
10.Further Readings
10.1 Web sites related to C++ tutorials about AVL and Heap trees
1. http://www.cs.uah.edu/~rcoleman/Common/CodeVault/Code/Code203_Tree.html
2. http://www.cplusplus.com/reference/algorithm/make_heap/
163