Professional Documents
Culture Documents
Student Data Struct Instructional Materials
Student Data Struct Instructional Materials
Student Data Struct Instructional Materials
LESSON #1
MEMORY, ABSTRACT DATA TYPES, AND ADDRESSES
Searching List – is one of many ways data structure help you manipulate data that is stored in
your computer’s memory.
Computer memory is divided into three sections:
1. Main memory
2. Cache memory in central processing unit
3. Persistent Storage.
Cache Memory in the CPU - used to store frequently used instructions and data that is either
is, will be, or has been used by the CPU.
System Bus
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Persistent Storage
• Is an external storage device such as hard disk that stores instructions and data.
• Non-volatile storage – instruction and data remain stored even when the computer is
power down.
• It is commonly used by the operating system as a virtual memory.
Virtual memory – is a technique an operating system uses to increase the main memory
capacity exceeded.
• Data used by your program is stored in memory and manipulated by various data
structure techniques, depending on the nature of your program.
• Memory is a bunch of electronic switches called transistors that can be placed in one of
two states: on or off.
• The state of a switch is meaningless unless you assign a value to each state, which you
do using the binary numbering system.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
FLOATING POINTc++
Floating point group are used to store real numbers in memory.
• A real number contains a decimal value.
• There are two kinds of floating point data types: float and double.
• The float abstract data type is a single precision number, and a double is a double
precision number. Precision of a number is the number of places after the decimal point
that contains an accurate value.
• A character abstract data type is represented as an integer value that corresponds to a
character set.
• A character set assigns an integer value to each character, punctuation, and symbol
used in a language.
Memory Address
• Imagine main memory as a series of seemingly endless boxes organized into groups of
eight. Each box holds a zero or one. Each group of eight boxes (1 byte) is assigned a
unique number called a memory address.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Reference:
C.A. Shaffer, A Practical Introduction to Data Structures and Algorithm Analysis: Second
Edition, Prentice Hall, Upper Saddle River, NJ, 2011.
LABORATORY ACTIVITY#1
1. Write a program that will accept an integer value and identify if it is odd or even and
positive or negative.
Sample output:
Enter a number: 4
4 is a positive even number.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #2
DECLARING OBJECTS AND VARIABLES
Memory is reserved by using a data type in a declaration statement. The form of a declaration
statement varies depending on the programming language you use.
int myVariable;
Data type - Tells how much memory to reserve and the kind of data that will be stored in that
memory location
Variable name - A name used within the program to refer to the contents of that memory
location
Semicolon - tells the computer this is an instruction (statement)
Abstract data types are divided into two categories, primitive data types and user-defined
data types. A primitive data type is defined by the programming language, such as the data
types you learned about in the previous chapter. Some programmers call these built-in data
types.
The other category of abstract data type, a user-defined data type, is a group of primitive data
types defined by the programmer.
The form used to define a user-defined data type varies depending on the programming
language used to write the program. Some programming languages, such as Java, do not
support user-defined data types. Instead, attributes of a class are used to group together
primitive data types.
In the C and C++ programming languages, you define a user-defined data type by defining a
structure.
When you want the group of primitive data types represented by the structure, you create
an instance of the structure.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Structure body open and close braces within which are primitive data types that are
declared when an instance of the structure is declared
Semicolon Tells the computer this is an instruction (statement)
The body of a structure can contain any combination of primitive data types
and previously defined user-defined data types depending on the nature of the data required by
your program. Here is a structure that defines a student record consisting of a student number
and grade. The name of this user-defined data type is StudentRecord:
struct StudentRecord
{
int studentNumber;
char grade;
};
You declare an instance of a user-defined data type using basically the same technique that you
used to declare a variable. However, you use the name of the structure in place of the name of
the primitive data type in the declaration station.
Let’s say that you want to create an instance of the StudentRecord structure defined in the
previous section. Here’s the declaration statement that you need to declare in your program:
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Data elements within the body of a structure are placed sequentially in memory when
an instance of the structure is declared within a program.
Elements of a data structure are accessed by using the name of the instance of the structure
and the name of the element separated by a dot operator. Let’s say that you want to assign the
grade A to the grade element of the myStudent instance of the StudentRecord structure. Here’s
how you would write the assignment statement:
myStudent.grade = 'A';
You use elements of a structure the same way you use a variable within your program except
you must reference both the name of the instance and the name of the element in order to
access the element.
QUESTION:
What will be the output of the Sample Program #1?
EXPLAIN ORALLY.
Structures are used in procedure languages such as C. Object-oriented languages such as C++
and Java use both structures and classes to group together.
A class definition is a stencil similar in concept to a structure definition in that both use the
definition to create instances. A structure definition creates an instance of a structure, while a
class definition creates an instance of a class.
A class definition translates attributes and behaviors of a real life object into a simulation of that
object within a program. Attributes are data elements similar to elements of a structure.
Behaviors are instructions that perform specific tasks known as either methods or functions,
depending on the programming language used to write the program.
Defining a Class
A class definition resembles a definition of a structure, as you can see in the following example.
A class definition consists of four elements:
Class name The name used to uniquely identify the class and used to declare instances of a
class
Class body Open and close braces within which are primitive data types that are declared
when an instance of the class is declared and definitions of methods and functions that
are members of the class
Semicolon Tells the computer this is an instruction (statement)
The following class definition written in C++ defines the same student record that is defined in
the structure. However, the class definition also defines a function that displays the student
number and grade on the screen.
class StudentRecord
{
int studentNumber;
char grade;
void displayGrade()
{
cout<<"Student: " << studentNumber << " Grade: " << grade << endl;
}
};
You declare an instance of a class much the same way you declare a structure. That is, you use
the name of the class followed by the name of the instance of the class in a declaration
statement. Here is how an instance of the StudentRecord class is declared:
StudentRecord myStudent;
Memory is reserved for attributes of a class definition sequentially when an instance is declared,
much the same way as memory is reserved for elements of a structure.
Attributes, methods, and functions are referred to as members of a class. You access members
of an instance of a class using the name of the instance, the dot operator and the name of the
member, much the same ways as you access an element of a structure.
myStudent.grade = 'A';
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
myStudent.displayGrade();
Reference:
C.A. Shaffer, A Practical Introduction to Data Structures and Algorithm Analysis: Second
Edition, Prentice Hall, Upper Saddle River, NJ, 2011.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LABORATORY ACTIVITY#2
1. Create a class named Numbers with private and public (3 methods) declaration.
Method 1: Will identify if the inputted value is odd or even.
Method 2: Will identify if the inputted value is positive or negative.
Method 3: Will accept value which will be used for method 1 and 2.
Sample output:
Enter a number: -5
-5 is an odd number.
-5 is a negative number.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Pointer – is a variable and can be used as an element structure and as an attribute of class in
some programming languages such as C++. (Point to)
Reference Operator (&) – as soon as we declared variable, the amount of memory needed is
assigned for it at a specific location in memory (its memory address)
The address that locates a variable within memory is what we call a reference to that variable.
This can be obtained by preceding the identifier of a variable with an ampersand sign (&).
Ex. Ted = &Andy //This will assign to Ted the address of variable Andy (not talking the
content of the variable but the reference)
Ex. Andy = 25; // value 25 is assigned to Andy
Fred = Andy; // value of Andy assigned to Fred
Ted = &Andy; // Ted holds the address of Andy
Dereference Operator (*) – value pointed by.
Note:
A value referenced with & can be dereferenced with *
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
EXPLAIN ORALLY.
Reference:
C.A. Shaffer, A Practical Introduction to Data Structures and Algorithm Analysis: Second
Edition, Prentice Hall, Upper Saddle River, NJ, 2011.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LABORATORY ACTIVITY#3
Write a program that will accept 3 numbers and display the following:
a. The address of the inputted numbers using reference operator.
b. The address of the inputted numbers using pointer variable.
c. The address of the pointer variable using pointer to pointer variable.
d. The dereferenced value of pointer variable.
e. The dereferenced value of pointer to pointer variable.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #3
ARRAY
One of the simplest and most common types of data is the LIST.
A list is an ordered set consisting of a variable number of elements to which additions and
deletions may be made. A list which displays the relationship of physical adjacency is called
Linear List.
Ex:
Days of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
Values in a Deck of Cards
Floors of a building
The most common way of representing a linear list is through the use of an array.
An array may be defined as an ordered collection of data items of the same type referred to
collectively by a single name (the name of an array).
Array is a series of elements of the same type placed in contiguous memory locations that can
be individually referenced by adding an index to a unique identifier.
Syntax:
Data type name [size];
-Data type is a valid type (like int, float, etc.)
-Name is a valid identifier (array name)
-Size specifies how many elements the array has to contain
-Individual data items in an array is called elements
• NOTE: The elements field within brackets [] which represents the number of elements
the array is going to hold, must be a constant value, since arrays are blocks of non-
dynamic memory whose size must be determined before execution. In order to create
arrays with a variable length dynamic memory is needed.
Dimensionality of an Array
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
The following statement deletes the 8th element in an array called Arr1 which has the
size of 10 elements;
Arr1[8] = “ “; where 8 is the position of the element to be deleted.
Sample Program:
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
Oral Recitation:
Simulate the above code. What is the output? Explain.
Multidimensional arrays
Multidimensional arrays can be described as "arrays of arrays".
Sample Program:
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0;n<HEIGHT;n++)
for (m=0;m<WIDTH;m++)
{
jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
Reference:
C.A. Shaffer, A Practical Introduction to Data Structures and Algorithm Analysis: Second
Edition, Prentice Hall, Upper Saddle River, NJ, 2011.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LABORATORY ACTIVITY#4
1. Write a program that will accept 5 numbers and display it using array and a looping
statement.
2. Write a program that will accept 5 numbers and display the sum using array and a looping
statement.
3. Write a program that will accept 10 numbers and sort it in ascending and descending order
using array and a looping statement.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #4
Example: ~Cat();
Example:
Cat Rags; -gets no parameters (calls for default constructor)
Cat Frisky (5, 7); -cat constructor took two parameter
Cat Frisky (3); -cat constructor with one parameter
In the event that the constructor takes no parameters, you leave off the parentheses.
This is an exemption to the rule that states all functions require parentheses, even if they
take no parameters.
You don’t have to use the compiler provided constructor. You are always free to write
your own default constructor that is, a constructor with no parameters.
You are free to give your default constructor a function body in which you might initialize
the class.
NOTE: As a matter of form, if you declare a constructor, be sure to declare a destructor, even if
your destructor does nothing.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #5
STACK
• A stack is a list in which insertion and deletion take place at the same end
– This end is called top
– The other end is called bottom
Implementations of Stack
• Any list implementation could be used to implement a stack
– Arrays (static: the size of stack is given initially)
– Linked lists (dynamic: never become full)
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
class Stack {
public:
Stack(int size = 10); // constructor
~Stack() { delete [] values; } // destructor
bool IsEmpty() { return top == -1; }
bool IsFull() { return top == maxTop; }
double Top(); // examine, without popping
void Push(const double x);
double Pop();
void DisplayStack();
private:
int maxTop; // max stack size = size - 1
int top; // current top of stack
double* values; // element array
};
• Attributes of Stack
– maxTop: the max size of stack
– top: the index of the top element of stack
– values: point to an array which stores elements of stack
• Operations of Stack
– IsEmpty: return true if stack is empty, return false otherwise
– IsFull: return true if stack is full, return false otherwise
– Top: return the element at the top of stack
– Push: add an element to the top of stack
– Pop: delete the element at the top of stack
– DisplayStack: print all the data in the stack
Note:
Although the constructor dynamically allocates the stack array, the stack is still static. The size
is fixed after the initialization.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Push Stack
Pop Stack
• double Pop()
– Pop and return the element at the top of the stack
– Don’t forget to decrement top
double Stack::Pop() {
if (IsEmpty()) { //if stack is empty, print error
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
return values[top--];
}
}
Top Stack
• double Top()
– Return the top element of the stack
– Unlike Pop, this function does not remove the top element
double Stack::Top() {
if (IsEmpty()) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return values[top];
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Print Stack
• void DisplayStack()
– Print all the elements
void Stack::DisplayStack() {
cout << "top -->";
for (int i = top; i >= 0; i--)
cout << "\t|\t" << values[i] << "\t|" << endl;
cout << "\t|---------------|" << endl;
}
Using Stack
int main(void) {
Stack stack(5);
stack.Push(5.0);
stack.Push(6.5);
stack.Push(-3.0);
stack.Push(-8.0);
stack.DisplayStack();
cout << "Top: " << stack.Top() << endl;
stack.Pop();
cout << "Top: " << stack.Top() << endl;
while (!stack.IsEmpty()) stack.Pop();
stack.DisplayStack();
return 0;
}
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
while (!stackobject.empty())
{
cout<<”popping:”;
cout<<stackobject.top()<<endl;
stackobject.pop();
}
return 0;
}
Reference:
* Kent, J. (2012). Data Structures Demystified: A Self-Teaching Guide.
McGraw-Hill/Osborne.
* Kent, J. (2013). C++ Demystified: A Self-Teaching Guide. McGraw-Hill/Osborne.
Quiz:
LABORATORY ACTIVITY#5
1. Write a program that will accept 5 numbers and display it using stack.
2. Write a program that will accept 5 numbers and display the sum using stack.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #6
QUEUE
Like a stack, a queue is also a list. However, with a queue, insertion is done at one end, while
deletion is performed at the other end.
* Accessing the elements of queues follows a First In, First Out (FIFO) order.
* Like customers standing in a check-out line in a store, the first customer in is the first
customer served.
When enqueuing, the front index is always fixed and the rear index moves forward in the array.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
When dequeuing, the front index is fixed, and the element at the front the queue is removed.
Move all the elements after it by one position.
Implementation of Queue
* Dynamic queues have the same advantages over static queues as dynamic stacks have
over static stacks.
Linked Lists
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Class Node
class Node {
public:
double data; // data
Node* next; // pointer to next
};
Class List
class List {
public:
List(void) { head = NULL; } // constructor
~List(void); // destructor
bool IsEmpty() { return head == NULL; }
Node* InsertNode(int index, double x);
int FindNode(double x);
int DeleteNode(double x);
void DisplayList(void);
private:
Node* head;
};
• Operations of List
– IsEmpty: determine whether or not the list is empty
– InsertNode: insert a new node at a particular position
– FindNode: find a node with a given value
– DeleteNode: delete a node with a given value
– DisplayList: print all the nodes in the list
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Steps
1. Locate index’th element
2. Allocate memory for the new node
3. Point the new node to its successor
4. Point the new node’s predecessor to the new node
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Finding a Node
• int FindNode(double x)
– Search for a node with the value equal to x in the list.
– If such a node is found, return its position. Otherwise, return 0.
int List::FindNode(double x) {
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
currNode = currNode->next;
currIndex++;
}
if (currNode) return currIndex;
return 0;
}
Deleting a Node
• int DeleteNode(double x)
– Delete a node with the value equal to x from the list.
– If such a node is found, return its position. Otherwise, return 0.
• Steps
– Find the desirable node (similar to FindNode)
– Release the memory occupied by the found node
– Set the pointer of the predecessor of the found node to the successor of the
found node
• Like InsertNode, there are two special cases
– Delete first node
– Delete the node in middle or at the end of the list
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
int List::DeleteNode(double x) {
Node* prevNode = NULL; Try to find the
Node* currNode = head; node with its
int currIndex = 1; value equal to x
while (currNode && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode) {
if (prevNode) {
prevNode->next = currNode-next;
delete currNode;
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
• void DisplayList(void)
– Print the data of all the elements
– Print the number of the nodes in the list
void List::DisplayList()
{
int num = 0;
Node* currNode = head;
while (currNode != NULL){
cout << currNode->data << endl;
currNode = currNode->next;
num++;
}
cout << "Number of nodes in the list: " << num << endl;
}
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
• ~List(void)
– Use the destructor to release all the memory used by the list.
– Step through the list and delete each node one by one.
List::~List(void) {
Node* currNode = head, *nextNode = NULL;
while (currNode != NULL)
{
nextNode = currNode->next;
// destroy the current node
delete currNode;
currNode = nextNode;
}
}
Using List
int main(void)
{
List list;
list.InsertNode(0, 7.0) ; // successful
list.InsertNode(1, 5.0); // successful
list.InsertNode(-1, 5.0); // unsuccessful
list.InsertNode(0, 6.0); // successful
list.InsertNode(8, 4.0); // unsuccessful
// print all the elements
list.DisplayList();
if(list.FindNode(5.0) > 0) cout << "5.0 found" << endl;
else cout << "5.0 not found" << endl;
if(list.FindNode(4.5) > 0) cout << "4.5 found" << endl;
else cout << "4.5 not found" << endl;
list.DeleteNode(7.0);
list.DisplayList();
return 0;
}
6
Sample Execution. 7
5
Number of nodes in the list:
3
5.0 found
4.5 not found
6
5
Number of nodes in the list:
2
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
• Linked lists are more complex to code and manage than arrays, but they have some
distinct advantages.
– Dynamic: a linked list can easily grow and shrink in size.
• We don’t need to know how many nodes will be in the list. They are
created in memory as needed.
• In contrast, the size of a C++ array is fixed at compilation time.
– Easy and fast insertions and deletions
• To insert or delete an element in an array, we need to copy to temporary
variables to make room for new elements or close the gap caused by
deleted elements.
• With a linked list, no need to move other nodes. Only need to reset some
pointers.
Reference:
* Kent, J. (2012). Data Structures Demystified: A Self-Teaching Guide.
McGraw-Hill/Osborne.
* Kent, J. (2013). C++ Demystified: A Self-Teaching Guide. McGraw-Hill/Osborne.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Interactive Discussion:
Quiz:
1. Elaborate the advantages and disadvantages of implementing stack and queue with array
and linked lists.
LABORATORY ACTIVITY#5
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #6
RECURSION
• In some problems, it may be natural to define the problem in terms of the problem itself.
• Recursion is useful for problems that can be represented by a simpler version of the
same problem.
• Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
The factorial function is only defined for positive integers. So we should be a bit more
precise:
n! = 1 (if n is equal to 1)
n! = n * (n-1)! (if n is larger than 1)
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
For certain problems (such as the factorial function), a recursive solution often leads to
short and elegant code. Compare the recursive solution with the iterative solution:
To trace recursion, recall that function calls operate as a stack – the new function is put
on top of the caller.
– calling a function consumes more time and memory than adjusting a loop
counter.
– high performance applications (graphic action games, simulations of nuclear
explosions) hardly ever use recursion.
In less demanding applications recursion is an attractive alternative for iteration (for the
right problems!).
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LABORATORY ACTIVITY#6
1. Write a program that will compute for the factorial of the inputted value using recursive
solution and iterative solution.
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
• Fibonacci numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,… where each number is the sum of the preceding two.
• Recursive definition:
– F(0) = 0;
– F(1) = 1;
– F(number) = F(number-1)+ F(number-2);
//Calculate Fibonacci numbers using recursive function.
//A very inefficient way, but illustrates recursion well
int fib(int number)
{
if (number == 0) return 0;
if (number == 1) return 1;
return (fib(number-1) + fib(number-2));
}
Board Work:
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
int fib(int n)
{
int f[n+1];
f[0] = 0; f[1] = 1;
for (int i=2; i<= n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}
Recitation:
Quiz:
1. Write a program that will display the sequence of Fibonacci number up to the
inputted value.
Sample Output:
Enter a number: 8
Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
return 0;
}
Recitation:
Simulate and explain the logic of the given code.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
int main() {
int num_disc; //number of discs
Activity:
Reference:
* Kent, J. (2012). Data Structures Demystified: A Self-Teaching Guide.
McGraw-Hill/Osborne.
* Kent, J. (2013). C++ Demystified: A Self-Teaching Guide. McGraw-Hill/Osborne.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LABORATORY ACTIVITY#7
2. Write a program that will accept series of numbers and will identify the number of zeroes
among the values using recursive solution.
Sample Output:
Enter value:
10200
Number of zeroes: 3
2. Write a program that will accept value for base and exponent and display the answer
using recursive solution.
Sample Output:
Value for base: 5
Value for exponent: 2
Answer: 25
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
LESSON #7
GRAPHS
A graph data structure may also associate to each edge some edge value, such
as a symbolic label or a numeric attribute (cost, capacity, length, etc.).
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Representations
Different data structures for the representation of graphs are used in practice:
Adjacency list
Vertices are stored as records or objects, and every vertex stores a list of adjacent
vertices. This data structure allows the storage of additional data on the vertices.
Additional data can be stored if edges are also stored as objects, in which case each
vertex stores its incident edges and each edge stores its incident vertices.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Adjacency matrix
A two-dimensional matrix, in which the rows represent source vertices and columns
represent destination vertices. Data on edges and vertices must be stored externally.
Only the cost for one edge can be stored between each pair of vertices.
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year
Path
Path is a sequence of vertices.
The length of a path is the number of edges on the path.
Types of Path
A path is simple if and only if it does not contain a vertex more than once.
A path is a cycle if the beginning and end is the same vertex.
Reference:
* Kent, J. (2012). Data Structures Demystified: A Self-Teaching Guide.
McGraw-Hill/Osborne.
* Kent, J. (2013). C++ Demystified: A Self-Teaching Guide. McGraw-Hill/Osborne.
Activity:
LABORATORY ACTIVITY#8
RUBRICS:
Functionality - 50%
Logic - 30%
Time - 20%
100%
Grace S.
Ibanez
COSC 60 - Instructor