Title: COMP103 Extra Tutorial
1COMP103 Extra Tutorial
2Review Outline
- C programming basics
- Pointers
- Classes
- Linked lists
- Stacks
- Queues
3C programming basics
- Primitive variable types
- char, int, double, bool
- Declaration of variables
- lttypegt ltidentifiergt
- e.g. char ch int i doube d bool b
- Initialization of variables
- lttypegt ltidentifiergt ltvaluegt
- e.g. char chc int i0 double d1.2 bool
btrue
4C programming basics
- Manipulation of variables
- Assignments
- e.g. chb i1 d2.4 bfalse
- Operations (type specific)
- e.g. chc i2 1.2d bfalse
- Assignments Operations
- ch chc
- int j i2
- d / 2
- b !b
5C programming basics
- Control flow
- Branching
- if
- if-else
- if-else if-else
6C programming basics
- Control flow
- Looping
- while while(condition)
- checks condition each time before running the
same procedure(s) - do-while dowhile(condition)
- checks condition each time after running the same
procedure(s) - for for(int i0ilt8i)
- usually works with a counter
7C programming basics
- Functions
- Needs
- Input parameter list (can be a list, or nothing)
- Name (follows the naming rules of identifiers)
- Return value type (any variable type, or void)
- Body (inside a and a )
- Function prototype (declare before you use
it)lttypegt ltfunction namegt (lttype listgt)int
add(int, int) - Function definition (placed at any place)lttypegt
ltfunction namegt (parameter listgt)...int
add(int a, int b)int cab return c
8C programming basics
- Pass by value
- Function gets the input from its caller
byCaller passes the values as parameters - The function copies a clone of the passed
values and use it for its own
...void PrintSumAve(double,double)int main()
double x,y cin gtgt x gtgt y
PrintSumAve(x, y) return 0void
PrintSumAve(double no1, double no2) ...
9C programming basics
- Pass by reference
- Function gets the input from its caller
byCaller passes the values as parameters - The function uses the passed values directly for
its own
Passed by value
Passed by reference
...void PrintSumAve(double,double)int main()
double x,y,sum,mean cin gtgt x gtgt y
SumAve(x, y, sum, mean) return 0void
PrintSumAve(double no1, double no2, double sum,
double mean) ...
10C programming basics
- Arrays
- A way to store several number of values of the
same type, using just 1 identifier - When being passed to a function, the effect is
always pass-by-reference
A0
A1
A2
A3
A4
A5
A6
A7
int A8 1, 2, 3, 4, 5, 6, 7, 8
11C programming basics
- Two ways to set values in array
- Direct initialize during declaration
- Normal access
// declare an array storing 8 integers// and
give values to itint arrInt8
1,2,3,4,5,6,7,8
//declare an array storing 8 integers// and give
values to it using for-loopint
arrInt8for(int i0 ilt8 i) arrIntii1
12C programming basics
- Can have multi-dimensional array
- 1-D array
- 2-D array
int arrInt8 1, 2, 3, 4, 5, 6, 7, 8
char arrChar38 a,b,c,d,e,f,g
,h, i,j,k,l,m,n,o,p,
q,r,s,t,u,v,w,x
13C programming basics
- Structure (struct)A collection of related data
items, possibly of different types
struct StudentRecord char Name22
int ID char gender char Dept22
Name22
ID
gender
Dept22
14C programming basics
- Declare a struct variable the same way of a
normal variable - Use . to access data fields inside
StudentRecord student1, student2
strcpy(student1.Name, victor)student1.ID
123strcpy(student1.Dept, CSE)student1.gender
Mstrcpy(student2.Name, victoria)studen
t2.ID 124strcpy(student2.Dept,
CSE)student2.gender F
15Pointers
- A pointer is a variable used to store the address
of a memory cell/location, which holds the value
of some datatypes
16Pointers
- When a variable is declared, the program
allocates a memory space to store it, which can
be accessed via its - identifier, or
- address, through using pointers
- Since different variable types need different
memory sizes, a pointer should come with a type
as well
17Pointers
- Usage
- To have a pointer pointing to a variables
addressltvariable_typegt ltidentifiergt - To let a pointer store the address of a
variableltidentifiergt ltvariable_identifiergt - To use the value pointed to by the pointer, also
known as de-referencingltpointer_identifiergt - Example
- int i 100 int p pi
i
p
100
18Pointers
- Since pointer is just a variable storing the
location of another variable, we can go one step
further - Pointer to pointerA pointer pointing to another
pointer, which points to somewhere else
19Pointers
- Arrays used in C is just a continuous list of
memory spaces - When we have int a5,
- we are having a continuous list of memory spaces
for 5 integers - a actually stores the address of the first integer
20Pointers
- Using pointers in arraysint a5 2,4,6,8,22
- With a we have
- a giving the address of array a
- a de-referencing the address and giving the
value of the first element - ai giving the value of i-th element
- (ai) de-referencing the address given by
of the i-th element
a
21Pointers
- Pointer arithmetic can be used to navigate
throughout the array - int a5 2,4,6,8,22 int p a1
- p stores the address of the first element of a
- p0 is actually a1
- p1 gives the address of the next (second)
element - p-1 gives the address of the previous (first)
element
a
p
22Pointers
- Given a pointer p, pn refers to the element that
is offset from p by n positions
p - 1
a
p
a 1
p 1
a 2
p 2
a 3
p 3
a 4
23Pointers
- An advanced use of pointer to pointer is to have
a pointer pointing to a array of pointers - The result is a 2-D array (table)
- Exampleint a1,2,3, b4,5,6,
c7,8,9//an array of integer pointersint
p3 p0a p1b p2c//points to an
int type int table p
table
p
a
b
c
24Pointers
- Produce the effect of pass-by-reference
...void PrintSumAve(double,double)int main()
double x,y,sum,mean cin gtgt x gtgt y
SumAve(x, y, sum, mean) return 0void
PrintSumAve(double no1, double no2, double sum,
double mean) sum no1 no2 mean
sum/2...
...void PrintSumAve(double,double)int main()
double x,y,sum,mean cin gtgt x gtgt y
SumAve(x, y, sum, mean) return 0void
PrintSumAve(double no1, double no2, double sum,
double mean) sum no1 no2 mean
sum/2...
25Pointers
- A pointer can be used to point to a dynamic
object, which is un-named - Usage
- ltpointergt new ltvariable_typegt
- E.g. int p p new int
26Pointers
- Besides a single variable, a dynamic object can
also be an un-named array - Usage
- ltpointergt new ltvariable_typegtexpression
- E.g. int p, n5 p new intn
Uninitialized int variable
p
27Pointers
- Dynamic objects have to be removed via their
pointers, since they have no names - Usage
- //free up memory for a variabledelete
ltpointer_identifiergt - //free up memory for an arraydelete
ltpointer_identifiergt - E.g. int p p new int delete pint q, n5
q new intn delete q
28Pointers
- 2 steps to create/delete dynamic 2-D array
//array of pointers,//1 pointer per rowint
table new intm
table
//create rowsfor(int i0 iltm i) tablei
new intn
//reverse steps to deletefor(int i0 iltm i)
delete tableidelete table
29Classes
- C supports the Object-oriented Programming
(OOP) paradigm - Things are modeled as objects with special
behaviors - In brief, a template class is defined and
instances of it are used as variables, with
extra functions included - Extra functions can be tailor-made for a specific
class
30Classes
class defined once
via constructors
objects used many
each object has its own sets of fields and
functions
31Classes
- A typical class has the following functions
- Constructors to create an instance
- Destructors to release allocated memory
- Accessor functions to use/modify/inspect member
fields of an object
32Classes
- Constructor
- special class member function that is used to
initialize an object automatically when the
object is defined - called automatically when an object is defined
- 3 formats
- Default constructor without parameters
- Parameterized constructor with 1 or more
parameters - Copy constructor takes another object of same
class as parameter (for deep copy)
33Classes
- Destructor
- a special class member function that de-allocates
the memory for private and public member
variables of an object - Where we put the deletes if we have new-ed
anything - is automatically called by C whenever the block
of code in which an class object is declared,
i.e. scope, ends
34Classes
- Accessor functions
- Public member functions that access (get or set)
the values of the private member data values of
an object - Private members are inaccessible to functions
outside the class (encapsulation of OOP) - Invoked by using the dot notation to call the
access functions and get the results
35Linked lists
- A way to store as many data as one wants, limited
by system memory - Basic unit node
- Stores 1 data item (e.g. int, string, struct)
- Stores where the next node is
address of next node
data item
36Linked lists
- Works like LEGO, add one node to the end (or
front) for each new data item - The only way to know where the next node is, is
to check the previous node - The location of the first node is stored by a
pointer (usually called head) - NULL is a special value which indicates the
pointer is pointing to nothing
head
NULL
20
45
75
85
37Linked lists
- Typical linked lists are implemented as a class
to support linked list operations
class listClass public listClass() //
constructor listClass(const listClass
list1) listClass() // destructor bool
empty() const // boolean function int
headElement() const // access functions void
addHead(int newdata) // add to the head void
delHead() // delete the head int search()
const //search function int length() const
// utility function void print() const //
output private Nodeptr Head
struct Node int data Node
next typedef Node NodePtr
38Linked lists
- Insertion listClassaddHead(int newdata)
- Create a node for the new data item
- Make that node as first node, 2 cases
- Empty list head points to it, done
- Non-empty list it points to original first
node, head points to it, done
Case i
Case ii
newPtr
newPtr
NULL
NULL
20
20
head
NULL
head
39Linked lists
- Deletion listclassdelHead()
- Find a pointer to point to the first node (to be
deleted) - Make the head pointer point to its next node
- Delete the node
delPtr
head
40Linked lists
- Search listClasssearch(int data)
- Create a pointer to a node, starting at first
node - Use a loop to travel through the list, compare
and report if match, or reach the end of list
head
NULL
20
45
75
85
41Linked lists
- It is possible to insert or delete a node in
between the list - Find the place to insert or delete
- Keep track of the previous and next nodes
- Have to determine working on the first node or
not - Need to modify head pointer if so
42Linked list
newPtr
NULL
45
prevPtr
nextPtr
head
NULL
20
75
85
delPtr
prevPtr
nextPtr
head
NULL
20
75
85
43Linked lists
- Variants of linked lists
- Circular linked lists
- Last node points back to first node
- Doubly linked lists
- Each node points to previous node as well
Rear
20
Head
Cur-gtnext
Cur-gtprev
Cur
44Linked lists
- Things to take care of
- When changing a pointer, make sure there is
another pointer pointing to the node - Always check if the list is empty (headNULL)
- When using loop to go through the list, keep
checking NULL to see when to end
45Stacks
- Another way to store as many data items as one
wants, with the LIFO property - LIFO Last In First Out
- You cannot get data items in the middle
Push(S,A)
Push(S,B)
Push(S,C)
Pop(S)
Push(S,D)
Pop(S)
Pop(S)
46Stacks
- Only 2 operations to modify the contents of a
stack - Push to insert a data item
- Pop to get a data item, which is the most
recently inserted item - Can be used to reverse the order of the entire
list of data (why?) - Easily implemented using the linked list class
(why?)
47Queues
- Yet another way to store as many data items as
one wants, with the FIFO property - FIFO First In First Out
- You cannot get data items in the middle
Insert (Enqueue)
Remove(Dequeue)
rear
front
48Queues
- Only 2 operations to modify the contents of a
queue - Enqueu to insert a data item
- Dequeue to get a data item, which is the oldest
inserted item - Possible to implement using a linked list (how?)
49Queues
- Different ways to implement Enqueue and Dequeue
in an array (1) - Fixed front index and moving rear index
- Enqueue arrayrear value rear
- Dequeue output arrayfront shift one slot to
the left - Moving front index and moving rear index
- Enqueue same as above
- Dequeue output arrayfront front
50Queues
- Different ways to implement Enqueue and Dequeue
in an array (2) - Circular array using operator
3
6
front
9
rear