Student Data Struct Instructional Materials

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS

Lecture A.Y. 2020-2021 Mid-Year

LESSON #1
MEMORY, ABSTRACT DATA TYPES, AND ADDRESSES

Data Structure is a specialized format for organizing and storing data. General data


structure types include the array, stack, queue, the tree, and so on. Any data structure is
designed to organize data to suit a specific purpose so that it can be accessed and worked with
in appropriate ways.

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.

Main Memory - Also called the random access memory (RAM)

- is where instructions and data are stored.


- Main memory is volatile memory
Volatile memory - instruction and data contained in main memory are lost once the computer is
power down.

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.

Register – a segment of CPU cache memory.


- is a small amount of memory within the CPU the is used temporarily store
instructions and data.

System Bus

Bus – connects the CPU and Main memory.


- is a set of etched wires on the motherboard that is similar to a highway and transports
instructions and data between the CPU and the main memory.

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 and Memory

• 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.

Abstract Data Type

– is a keyword of programming language that specifies the amount of memory needed to


store data and kind of data that is store in that memory location.
Variable – is a reference to the memory location that is reserved using the declaration
statement.

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

The Abstract Data Type Groups

Four data Type Group:


1. Integer – Store whole number and signed number.
2. Floating point – Stores real numbers.
3. Characters – Store a character. Ideal for storing names of things.
4. Boolean – Stores a true or false value.

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.

Boolean Abstract Data Type


• A Boolean abstract data type reserves memory to store a Boolean value, which is
true or false represented as a zero or one.
• Choose a Boolean whenever you need to store one of two possibilities in memory.

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

Real Memory Address


• Hexadecimal is a numbering system similar to the decimal
and binary numbering systems.
• Here is how memory address 258,425,506 is represented in hexadecimal notation
0x0F6742A2.

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;

There are three parts to this declaration statement:

 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)

Primitive Data Types and User-Defined Data Types

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.

Defining a User-Defined Data Type

A structure definition consists of four elements:

 struct Tells the computer that you are defining a structure


 Structure name The name used to uniquely identify the structure and used to
declare instances of a 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;
};

Declaring a User-Defined Data Type

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:

Sample Program #1:


#include <iostream>
using namespace std;
struct StudentRecord {
int studentNumber;
char grade;
};
void main()
{
StudentRecord myStudent;
myStudent.studentNumber = 10;
myStudent.grade = 'A';
cout << "grades: " << myStudent.studentNumber << " " << myStudent.grade << endl;
}

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

User-Defined Data Types and Memory

Data elements within the body of a structure are placed sequentially in memory when
an instance of the structure is declared within a program.

Accessing Elements of a User-Defined Data Type

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.

User-Defined Data Type and Classes

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 Tells the computer that you are defining a class


Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

 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;
}
};

Declaring an Instance of a Class and a Look at Memory

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.

Accessing Members of a Class

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.

Here is how to access the grade attribute of the myStudent instance of the StudentRecord class


and call the displayGrade()method:

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.

4 parts of pointer declaration


1. Data type – type of the memory address store in the pointer.
2. Asterisk(*) – tells the computer that you are declaring a pointer.
3. Variable name – the name uniquely identifies the pointer and is used to reference the
pointer within the program.
4. Semicolon – tells the computer this is an instruction (statement).
Ex.
Beth=Ted; //Beth equal to Ted;
Beth = *Ted; //Beth equal to value pointed by Ted;

Note:
A value referenced with & can be dereferenced with *

Example program #1:


#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int *mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer=&secondvalue;
*mypointer = 20;

cout<<”first value is “<<firstvalue<<endl;


cout<<”second value”<<secondvalue<<endl;
return 0;}
Sample Execution: first value is 10
second value is 20

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

Example program #2:


#include <iostream>
using namespace std;
int main ()
{
int firstvalue=5, secondvalue=15;
int *p1, *p2;
p1=&firstvalue; //p1 is the address of the first value
p2=&secondvalue; //p2 is the address of the second value
*p1=10; //value pointed by p1 = 10
*p2=*p1; //value pointed by p2 = value pointed by p1
p1=p2; //value of pointer is copied
*p1=20; //value pointed by p1 = 20

cout<<"The first value is "<<firstvalue<<endl;


cout<<"second value is "<<secondvalue<<endl;
return 0;
}

QUESTION: What will be the output of the example program #2?


ANSWER:

EXPLAIN ORALLY.

TOPIC 2: POINTER TO POINTER


A pointer to pointer is also a variable that contains the memory address, except that it contains
the memory address of another pointer variable.
A pointer to pointer is declared using double asterisks.
Ex.
char initial1=’D’, initial2=’C’, initial3=’B’, initial4=’A’;
char *ptinitial, **ptptinitial;
ptinitial=&initial1;
ptptinitial=&ptinitial;

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.

A Linear List is a finite sequence of simple data items or records.

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

• Number of subscripts of an array


One Dimensional Array – Array1[j];
Multi-dimensional Array – “arrays of arrays” - Array1[i][j];

Storing a New Value into an element of a One-dimensional Array


Using an array Arr1 which has a size of 10,the following statement sets the 4 th element
to “Apples”. where: 4 = element position
Arr1[4] = “Apples”; “Apples” = New Value
Note: When storing values in an array, the subscript use to specify the element’s position
should never exceed the size of the array.
Deleting an Element from one-dimensional 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

CONSTRUCTORS AND DESTRUCTORS

 Classes have a special member function called constructor.


 The constructor can take parameters as needed, but it cannot have a return value – not
even void.
 The constructor is a class method with the same name as the class itself.
 Just as constructors create and initialize objects of your class, destructors clean up after
your object and free any memory you might have allocated.
 A destructor always has the same name of the class, preceded by a tilde(~).

Example: ~Cat();

Default Constructors and Destructors


 If you don’t declare constructors or destructors, the compiler makes one for you.
 The default constructor and destructor take no arguments and do nothing.
 Using the default constructor – declare an object without passing in parameters:

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 basic data structure that can be logically thought as linear


structure represented by a real physical stack or pile, a structure where insertion and deletion of
items takes place at one end called top of the 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

• Stacks are known as LIFO (Last In, First Out) lists.


– The last element inserted will be the first to be retrieved

• Primary operations: Push and Pop


• Push
– Add an element to the top of the stack
• Pop
– Remove the element at the top of the stack

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)

• Let’s see how to use an array to implement a stack first

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

Stack class (As User-defined data type)

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

The constructor of Stack

– Allocate a stack array of size. By default,


size = 10.
– Initially top is set to -1. It means the stack is empty.
– When the stack is full, top will have its maximum value, i.e. size – 1.

Stack::Stack(int size /*= 10*/) {


values = new double[size];
top = -1;
maxTop = size - 1;
}

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

• void Push(const double x);


– Push an element onto the stack
– Note top always represents the index of the top element. After pushing an element,
increment top.

void Stack::Push(const double x) {


if (IsFull()) // if stack is full, print error
cout << "Error: the stack is full." << endl;
else
values[++top] = x;
}

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

Sample Stack Program as Abstract Data Type


#include<iostream>
#include<stack>
using namespace std;
int main ()
{
stack <char> stackobject;
stackobject.push(‘a’);
stackobject.push(‘b’);
stackobject.push(‘c’);
stackobject.push(‘d’);

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:

1. Explain the concept of Stack.


2. Explain the two basic operations of stack. _
3. Explain the difference between the two implementations of stack. _

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

A queue is an example of a linear data structure, or more abstractly a sequential collection. 

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.

Enqueue and Dequeue

* Primary queue operations: Enqueue and Dequeue


* Like check-out lines in a store, a queue has a front and a rear.
* Enqueue – insert an element at the rear of the queue
* Dequeue – remove an element from the front of the queue

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

* Just as stacks can be implemented as arrays or linked lists, so with queues.

* Dynamic queues have the same advantages over static queues as dynamic stacks have
over static stacks.

Linked Lists

In computer science, a linked list is a data structure consisting of a group


of nodes which together represent a sequence. Under the simplest form, each node is
composed of data and a reference (in other words, a link) to the next node in the sequence;
more complex variants add additional links.

• Basic operations of linked lists


• Insert, find, delete, print, etc.
• Variations of linked lists
• Circular linked lists
• Doubly linked lists
• A linked list is a series of connected nodes
• Each node contains at least
• A piece of data (any type)
• Pointer to the next node in the list
• Head: pointer to the first node
• The last node points to NULL

A Simple Linked List Class

• We use two classes: Node and List


• Declare Node class for the nodes
– data: double-type data in this example
– next: a pointer to the next node 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

Class Node

class Node {
public:
double data; // data
Node* next; // pointer to next
};

Class List

• Declare List, which contains


– head: a pointer to the first node in the list.
Since the list is empty initially, head is set to NULL
– Operations on 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

Inserting a New Node


Node* InsertNode(int index, double x)
– Insert a node with data equal to x after the index’th elements. (i.e., when index =
0, insert the node as the first element;
when index = 1, insert the node after the first element, and so on)
– If the insertion is successful, return the inserted node.
Otherwise, return NULL.
(If index is < 0 or > length of the list, the insertion will fail.)

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

• Possible cases of InsertNode


1. Insert into an empty list
2. Insert in front
3. Insert at back
4. Insert in middle
• But, in fact, only need to handle two cases
1. Insert as the first node (Case 1 and Case 2)
2. Insert in the middle or at the end of the list (Case 3 and Case 4)

Node* List::InsertNode(int index, double x) { Try to locate the index


if (index < 0) return NULL; node. If it doesn’t exist
return null.
int currIndex = 1;
Node* currNode = head;
while (currNode && index > currIndex) {
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL) return NULL; Create new Node

Node* newNode = new Node;


newNode->data = x;
Insert as first element
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next; Insert after currNode
currNode->next = newNode;
}
return newNode;
}

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;
}

Printing all the Elements

• 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

Destroying the List

• ~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

Variations of Linked List

• Circular linked lists


– The last node points to the first node of the list
– How do we know when we have finished traversing the list? (Tip: check if the
pointer of the current node is equal to the head.)

• Doubly linked lists


– Each node points to not only successor but the predecessor
– There are two NULL: at the first and last nodes in the list
– Advantage: given a node, it is easy to visit its predecessor. Convenient to
traverse lists backwards

Array vs. Linked List

• 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:

Simulate each method of the declared class.


Explain the logic and codes.

Quiz:
1. Elaborate the advantages and disadvantages of implementing stack and queue with array
and linked lists.

LABORATORY ACTIVITY#5

1. Write a program that will produce the following output:

CHOICES: CHOICES: ENTER CHOICE: 3


1 ENQUEUE 1 ENQUEUE
2 DEQUEUE 2 DEQUEUE DISPLAY:
3 DISPLAY 3 DISPLAY List content:
4 QUIT 4 QUIT 3
ENTER CHOICE: 3 ENTER CHOICE: 1 4
7
DISPLAY: ENQUEUE: 9
The list is empty. Number of elements to
insert: 4 CHOICES:
CHOICES: Enter 4 numbers: 3 1 ENQUEUE
1 ENQUEUE 4 2 DEQUEUE
2 DEQUEUE 7 3 DISPLAY
3 DISPLAY 9 4 QUIT
4 QUIT ENTER CHOICE: 4
ENTER CHOICE: 2 CHOICES:
1 ENQUEUE QUIT: Are you sure you
DEQUEUE: 2 DEQUEUE want to quit? [y/n] y
The list is empty. 3 DISPLAY
4 QUIT

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!

Application #1: Factorial Function

Factorials are very simple things. They're just products, indicated by an exclamation


mark. For instance, "four factorial" is written as "4!" and means 1×2×3×4 = 24. In general, n!
("enn factorial") means the product of all the whole numbers from 1 to n; that is, n! =
1×2×3×...×n.

In general, we can express the factorial function as follows:


n! = n * (n-1)!

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)

The C++ equivalent of this definition:

int fac(int numb){


if(numb<=1)
return 1;
else
return numb * fac(numb-1);
}

Recursion means that a


function calls itself.

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:

Recursive solution Iterative solution

int fac(int numb){ int fac(int numb){


if(numb<=1) int product=1;
return 1; while(numb>1){
else product *= numb;
numb--;
return numb*fac(numb-1);
}
} return product;
}

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!).

If we use iteration, we must be careful not to create an infinite loop by accident:

for(int incr=1; incr!=10;incr+=2) Oooopss!


...
Where is the infinite loop
int result = 1; here?
while(result >0){
...
result++;
}
Similarly, if we use recursion we must be careful not to create an infinite chain of function calls:

int fac(int numb){


return numb * fac(numb-1);
} Oooopss!

Or: Where is the infinite chain of


function call?
int fac(int numb){
if (numb<=1)
return 1;
else
return numb * fac(numb+1);
}

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

We must always make sure that the recursion bottoms out:


• A recursive function must contain at least one non-recursive branch.
• The recursive calls must eventually lead to a non-recursive branch.
• Recursion is one way to decompose a task into smaller subtasks. At least one of the
subtasks is a smaller example of the same task.
• The smallest example of the same task has a non-recursive solution.

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%

Application #2: Fibonacci

• 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));
}

int main() { // driver function


int inp_number;
cout << "Please enter an integer: ";
cin >> inp_number;
cout << "The Fibonacci number for "<< inp_number
<< " is "<< fib(inp_number)<<endl;
return 0;
}

Board Work:
Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

Create the class definition for the above program.

Fibonacci without Recursion

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:

Simulate the iterative solution for Fibonacci.

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

Application #3: Binary Search

– Search for an element in an array


• Sequential search
• Binary search
– Binary search
• Compare the search element with the middle element of the array
• If not equal, then apply binary search to half of the array (if not empty)
where the search element would be.

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

// Searches an ordered array of integers using recursion

int bsearchr(const int data[], // input: array


int first, // input: lower bound
int last, // input: upper bound
int value // input: value to find
)// output: index if found, otherwise return –1
{
int middle = (first + last) / 2;
if (data[middle] == value)
return middle;
else if (first >= last)
return -1;
else if (value < data[middle])
return bsearchr(data, first, middle-1, value);
else
return bsearchr(data, middle+1, last, value);
}
int main() {
const int array_size = 8;
int list[array_size]={1, 2, 3, 5, 7, 10, 14, 17};
int search_value;
cout << "Enter search value: ";
cin >> search_value;
cout << bsearchr(list,0,array_size-1,search_value)
<< endl;

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

Binary Search without Recursion

// Searches an ordered array of integers

int bsearch (const int data[], // input: array


int size, // input: array size
int value ) // input: value to find

{ // output: if found, return


// index; otherwise, return -1
int first, last, upper;
first = 0;
last = size - 1;
while (true) {
middle = (first + last) / 2;
if (data[middle] == value)
return middle;
else if (first >= last)
return -1;
else if (value < data[middle])
last = middle - 1;
else
first = middle + 1;
}
}

Grace S.
Ibanez
COSC 60 - Instructor
COSC 60 – Data Structures CAVITE STATE UNIVERSITY – IMUS CAMPUS
Lecture A.Y. 2020-2021 Mid-Year

Application #4: Tower of Hanoii

– Only one disc could be moved at a time


– A larger disc must never be stacked above a smaller one
– One and only one extra needle could be used for intermediate storage of discs

int main() {
int num_disc; //number of discs

cout << "Please enter a positive number (0 to quit)";


cin >> num_disc;

while (num_disc > 0){


hanoi(1, 3, num_disc);
cout << "Please enter a positive number ";
cin >> num_disc;
}
return 0;
}

Activity:

Write the class definition for the Tower of Hanoi program.

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

In computer science, a graph is an abstract data type that is meant to implement


the graph and directed graph concepts from mathematics.

A graph data structure consists of a finite (and possibly


mutable) set of nodes or vertices, together with a set of ordered pairs of these nodes
(or, in some cases, a set of unordered pairs). These pairs are known as edges or arcs.

As in mathematics, an edge (x,y) is said to point or go from x to y. The nodes


may be part of the graph structure, or may be external entities represented by integer
indices or references.

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

1. Write a program that will accept values for

RUBRICS:

Functionality - 50%
Logic - 30%
Time - 20%
100%

Grace S.
Ibanez
COSC 60 - Instructor

You might also like