Professional Documents
Culture Documents
Lab 01
Dynamic Memory Allocation
In this lab, we will learn how to allocate memory dynamically and de-allocate memory that is allocated dynamically.
Recall the syntax for the operators new and delete.
delete Pointer;
delete [] Pointer;
Example:
int *a = new int;
char *b = new char[5];
float *c = new float[3*someVariable+1];
double **d = new double*[10];
delete a;
delete [] b;
delete [] c;
delete [] d;
Before you begin: Create a C++ project. A project contains all the relevant files such as source codes, header files,
and relevant resources. Also, under CodeBlocks, you can only debug your program under a project; single-file
program debugging is not supported. Follow the steps below to create a project.
1. File ⇒ New ⇒ Project... ⇒ Console Application ⇒ Go.
2. The "Console Application" wizard appears:
a. Next
b. Select "C++" ⇒ Next.
c. In "Project Title", enter the name you want to assign to the project (for example lab01). In "Folder to
create project in", set to your working directory, (for example d:\labs). Accept the default for the rest ⇒
Next. A project directory "lab01" will be created under "d:\labs", with a project configuration filename
of "lab01.cbp". You could later create more projects under this working directory "d:\labs".
d. In "Compiler" field, accept the defaults of "GNU GCC Compiler" ⇒ Finish.
3. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node "lab01" ⇒ Expand
"Sources" node ⇒ Double-click "main.cpp", which is an example program to print "Hello, world!".
4. To build the program, select "Build" menu ⇒ Build.
5. To run the program, select "Build" menu ⇒ Run.
Tasks:
Task 1: Using the new operator, allocate an integer array of user specified size (the user gives the size of the array as
input). Assign values to the array elements by taking user inputs and then print the values. Finally de-allocate the array
using the delete operator.
Task 2: Using the new operator, allocate a two dimensional character array. Again the number of rows and columns
are going to be provided by the user as input. All of the rows are the same size. Take character strings as input from
the user and then print the strings. Finally de-allocate the array using the delete operator.
Task 3: Using the new operator, allocate a two dimensional integer array. The number of rows and columns are going
to be provided by the user as input. However, in this task, all of the rows are not the same size (the array is uneven).
The user will specify how many elements the individual rows will have. Assign values to the array elements by taking
user inputs and then print the values. Finally de-allocate the array using the delete operator.
CSE225L – Data Structures a nd Alg o rithms Lab
Lab 02
Classes & Objects
Recall the class for dynamic array we developed in our 2nd lecture. In this lab session, you will implement and test that
class.
Before you begin: Create a C++ project. Then create a header file and a source file for your project. Follow the steps
below to create files.
1. Create a header file.
a. File ⇒ New ⇒ File. Select C/C++ header. Select Go ⇒ Next.
b. Click the browse button beside the textbox labelled “Filename with full path”. A window appears. In
the textbox labelled “File name”, type in the name you want to assign to the header file (in this case
dynarr.h). Select Save ⇒ select All ⇒ select Finish.
c. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node ⇒ Expand
"Headers" node. You will see the file you just created. It is mostly blank except for a few lines of
code. It is time to add your own code to it. For your convenience, the content of this file is already
provided with this manual (refer to the table in the opposite page). Add the content of dynarr.h just
before the #endif statement.
2. Next, create the source file
a. File ⇒ New ⇒ File. Select C/C++ source. Select Go ⇒ Next.
b. Select "C++" ⇒ Next.
c. Click the browse button beside the textbox labelled “Filename with full path”. A window appears. In
the textbox labelled “File name”, type in the name you want to assign to the source file (in this case
dynarr.cpp). Select Save ⇒ select All ⇒ select Finish.
d. Under the "Management" pane ⇒ Choose "Projects" tab ⇒ Expand the project node ⇒ Expand
"Sources" node. You will see the file you just created. It is completely blank. It is time to add your
own code to it. For your convenience, the content of this file is already provided with this manual
(refer to the table in the opposite page). Add the content of dynarr.cpp to the newly created file.
3. In the opposite page, will find some tasks that you have to perform using the code provided. You have to
modify the file main.cpp and perform these task in that file.
4. To build the program, select "Build" menu ⇒ Build.
5. To run the program, select "Build" menu ⇒ Run.
dynarr.h dynarr.cpp
Tasks:
Task 2: Modify the header and the source files. Add a member function void allocate(int s) which allows
you to change the size of the array. Make sure that memory is not leaked.
Task 3: Modify the header file and the source files again, so that it works for two dimensional array where all the
rows are the same size. The user will specify the number of rows and columns as well as the content of the array,
which you will take as input from user in the main function.
CSE225L – Data Structures and Algorithms Lab
Lab 03
Template Class and Operator Overloading
Task 1: Recall the class we used in the previous lab to allocate memory dynamically. Modify the header file
and the source file given below so that they now work as template class (the array elements in the
dynamically allocated memory can be any type as the user defines).
dynarr.h dynarr.cpp
Task 2: Recall the complex number class we discussed in our lectures. Modify the class and overload the *
(multiplication) and the != (not equal) operators for the class given below.
complex.h complex.cpp
In today’s lab we will design and implement the List ADT where the items in the list are unsorted.
In today’s lab we will design and implement the List ADT where the items in the list are sorted.
In today’s lab we will design and implement the Stack ADT using array.
stacktype.h stacktype.cpp
In today’s lab we will design and implement the Queue ADT using array.
In today’s lab we will design and implement the Stack ADT using linked list.
stacktype.h template <class ItemType>
bool StackType<ItemType>::IsFull()
#ifndef STACKTYPE_H_INCLUDED {
#define STACKTYPE_H_INCLUDED NodeType* location;
class FullStack try
{}; {
class EmptyStack location = new NodeType;
{}; delete location;
template <class ItemType> return false;
class StackType }
{ catch(bad_alloc& exception)
struct NodeType {
{ return true;
ItemType info; }
NodeType* next; }
}; template <class ItemType>
public: void StackType<ItemType>::Push(ItemType newItem)
StackType(); {
~StackType(); if (IsFull())
void Push(ItemType); throw FullStack();
void Pop(); else
ItemType Top(); {
bool IsEmpty(); NodeType* location;
bool IsFull(); location = new NodeType;
private: location->info = newItem;
NodeType* topPtr; location->next = topPtr;
}; topPtr = location;
#endif // STACKTYPE_H_INCLUDED }
}
stacktype.cpp template <class ItemType>
void StackType<ItemType>::Pop()
#include <iostream> {
#include "stacktype.h" if (IsEmpty())
using namespace std; throw EmptyStack();
else
template <class ItemType> {
StackType<ItemType>::StackType() NodeType* tempPtr;
{ tempPtr = topPtr;
topPtr = NULL; topPtr = topPtr->next;
} delete tempPtr;
}
template <class ItemType> }
bool StackType<ItemType>::IsEmpty() template <class ItemType>
{ StackType<ItemType>::~StackType()
return (topPtr == NULL); {
} NodeType* tempPtr;
while (topPtr != NULL)
template <class ItemType> {
ItemType StackType<ItemType>::Top() tempPtr = topPtr;
{ topPtr = topPtr->next;
if (IsEmpty()) delete tempPtr;
throw EmptyStack(); }
else }
return topPtr->info;
}
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.
Operation to Be Tested and Description of Action Input Values Expected Output
• Take infix expressions from the user as input, 10 + 3 * 5 / (16 - 4) 11.25
determine the outcome of the expression and gives (5 + 3) * 12 / 3 32
that back to user as output, or the text “Invalid 3 + 4 / (2 - 3) * / 5 Invalid expression
expression” if the expression is not a valid one. You 7 / 5 + (4 - (2) * 3 Invalid expression
will have to solve this problem in two steps. First, you
have to convert the expression from infix notation to
postfix notation. You are going to need a stack in
order to do so. In the next step, you will have to
evaluate the postfix expression and determine the
final result. Again, you will need a stack in order to
do this. All the operands in the infix expressions are
single digit non-negative operands and the operators
include addition (+), subtraction (-), multiplication (*)
and division (/).
CSE225L – Data Structures and Algorithms Lab
Lab 09
Queue (Linked List)
In today’s lab we will design and implement the Queue ADT using linked list.
quetype.h template <class ItemType>
void QueType<ItemType>::Enqueue(ItemType newItem)
#ifndef QUETYPE_H_INCLUDED {
#define QUETYPE_H_INCLUDED if (IsFull())
class FullQueue throw FullQueue();
{}; else
class EmptyQueue {
{}; NodeType* newNode;
template <class ItemType> newNode = new NodeType;
class QueType newNode->info = newItem;
{ newNode->next = NULL;
struct NodeType if (rear == NULL)
{ front = newNode;
ItemType info; else
NodeType* next; rear->next = newNode;
}; rear = newNode;
public: }
QueType(); }
~QueType(); template <class ItemType>
void MakeEmpty(); void QueType<ItemType>::Dequeue(ItemType& item)
void Enqueue(ItemType); {
void Dequeue(ItemType&); if (IsEmpty())
bool IsEmpty(); throw EmptyQueue();
bool IsFull(); else
private: {
NodeType *front, *rear; NodeType* tempPtr;
}; tempPtr = front;
item = front->info;
#endif // QUETYPE_H_INCLUDED front = front->next;
quetype.cpp if (front == NULL)
rear = NULL;
#include "quetype.h" delete tempPtr;
#include <iostream> }
using namespace std; }
template <class ItemType>
template <class ItemType> void QueType<ItemType>::MakeEmpty()
QueType<ItemType>::QueType() {
{ NodeType* tempPtr;
front = NULL; while (front != NULL)
rear = NULL; {
} tempPtr = front;
template <class ItemType> front = front->next;
bool QueType<ItemType>::IsEmpty() delete tempPtr;
{ }
return (front == NULL); rear = NULL;
} }
template<class ItemType> template <class ItemType>
bool QueType<ItemType>::IsFull() QueType<ItemType>::~QueType()
{ {
NodeType* location; MakeEmpty();
try }
{
location = new NodeType;
delete location;
return false;
}
catch(bad_alloc& exception)
{
return true;
}
}
Generate the Driver file (main.cpp) and check your program with the following outputs:
Operation to Be Tested and Description of Action Input Values Expected Output
• Given a set of coin values and an amount of money, 3 2 3 5 11 3
determine the minimum number of coins to make the given 3 5 20 30 40 2
amount of money. The input starts with an integer n,
specifying the number of coin types. Next n integers are the
coin values. The final integer is the amount of money you
have to make. You can assume that the amount will always
be possible to make using the given coin types.
• Try the input 3 2 3 5 200. Explain your program’s outcome
with this input.
CSE225L – Data Structures and Algorithms Lab
Lab 10
Unsorted List (linked list based)
In today’s lab we will design and implement the List ADT where the items in the list are unsorted.
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.
In today’s lab we will design and implement the List ADT where the items in the list are sorted.
Generate the driver file (main.cpp) where you perform the following tasks. Note that you cannot make any change to
the header file or the source file.
1. Write a recursive function that returns the nth Fibonacci number from the Fibonacci
series.
int fib(int n);
3. Write a recursive function that returns the sum of the digits of an integer.
4. Write a recursive function that find the minimum element in an array of integers.
int findMin(int a[], int size);
6. Write a recursive function that find the sum of the following series.
1 + 1/2 + 1/4 + 1/8 + ... + 1/2n
CSE225L – Data Structures and Algorithms Lab
Lab 13
Binary Search Tree
In today’s lab we will design and implement the Binary Search Tree ADT.
Now generate the Driver file (main.cpp) where you perform the following tasks:
Hint: Sort the sequence (use the inorder traversal). The middle
element is the root. Insert it into an empty tree. Now in the
same way, recursively build the left subtree and then the right
subtree.
CSE225L – Data Structures and Algorithms Lab
Lab 14
Priority Queue
In today’s lab we will design and implement the Priority Queue ADT.
heaptype.h pqtype.h
#ifndef HEAPTYPE_H_INCLUDED #ifndef PQTYPE_H_INCLUDED
#define HEAPTYPE_H_INCLUDED #define PQTYPE_H_INCLUDED
template<class ItemType> #include "heaptype.h"
struct HeapType #include "heaptype.cpp"
{ class FullPQ
void ReheapDown(int root, int bottom); {};
void ReheapUp(int root, int bottom); class EmptyPQ
ItemType* elements; {};
int numElements; template<class ItemType>
}; class PQType
#endif // HEAPTYPE_H_INCLUDED {
heaptype.cpp public:
#include "heaptype.h" PQType(int);
template<class ItemType> ~PQType();
void Swap(ItemType& one, ItemType& two) void MakeEmpty();
{ bool IsEmpty();
ItemType temp; bool IsFull();
temp = one; void Enqueue(ItemType);
one = two; void Dequeue(ItemType&);
two = temp; private:
} int length;
template<class ItemType> HeapType<ItemType> items;
void HeapType<ItemType>::ReheapDown(int root, int bottom) int maxItems;
{ };
int maxChild; #endif // PQTYPE_H_INCLUDED
int rightChild; pqtype.cpp
int leftChild; #include "pqtype.h"
template<class ItemType>
leftChild = root*2+1; PQType<ItemType>::PQType(int max)
rightChild = root*2+2; {
if (leftChild <= bottom) maxItems = max;
{ items.elements=new ItemType[max];
if (leftChild == bottom) length = 0;
maxChild = leftChild; }
else template<class ItemType>
{ PQType<ItemType>::~PQType()
if(elements[leftChild]<=elements[rightChild]) {
maxChild = rightChild; delete [] items.elements;
else }
maxChild = leftChild; template<class ItemType>
} void PQType<ItemType>::MakeEmpty()
if (elements[root] < elements[maxChild]) {
{ length = 0;
Swap(elements[root], elements[maxChild]); }
ReheapDown(maxChild, bottom); template<class ItemType>
} bool PQType<ItemType>::IsEmpty()
} {
} return length == 0;
template<class ItemType> }
void HeapType<ItemType>::ReheapUp(int root, int bottom) template<class ItemType>
{ bool PQType<ItemType>::IsFull()
int parent; {
if (bottom > root) return length == maxItems;
{ }
parent = (bottom-1) / 2;
if (elements[parent] < elements[bottom])
{
Swap(elements[parent], elements[bottom]);
ReheapUp(root, parent);
}
}
}
template<class ItemType> template<class ItemType>
void PQType<ItemType>::Enqueue(ItemType newItem) void PQType<ItemType>::Dequeue(ItemType& item)
{ {
if (length == maxItems) if (length == 0)
throw FullPQ(); throw EmptyPQ();
else else
{ {
length++; item = items.elements[0];
items.elements[length-1] = newItem; items.elements[0] =
items.ReheapUp(0, length-1); items.elements[length-1];
} length--;
} items.ReheapDown(0, length-1);
}
}
Now generate the Driver file (main.cpp) where you perform the following tasks:
H G
E D
A
C