Week 1_ Introduction
Week 1_ Introduction
Week 1: Introduction
COMP9024 24T1
This term, your Teaching Team consists of ...
Course Goals
Pre-conditions
Post-conditions
Access to Course Material
Schedule (topics are not absolutely fixed ...)
Resources
Lectures
Weekly Practicals
Weekly Tutorials (problem sets)
Large Assignment
Plagiarism
Mid-term Test
Final Exam
Assessment Summary
Summary
C Programming Language
Why C?
Brief History of C
Basic Structure of a C Program
Exercise: What does this program compute?
Example: Insertion Sort in C
Compiling with gcc
Sidetrack: Printing Variable Values with printf()
Algorithms in C
Basic Elements
Assignments
Exercise: What are the final values of a and b?
Conditionals
Exercise: Conditionals
Loops
Exercise: What is the output of this program?
Functions
Data Structures in C
Basic Data Types
Aggregate Data Types
Arrays
Sidetrack: C Style
Strings
Array Initialisation
Exercise: What is the output of this program?
Sidetrack: Reading Variable Values with scanf() and atoi()
Arrays and Functions
Exercise: Arrays and Functions
Multi-dimensional Arrays
Sidetrack: Defining New Data Types
Structures
Data Abstraction
Abstract Data Types
ADOs and ADTs
Example: Abstract Stack Data Object
Stack vs Queue
Exercise: Stack vs Queue
Stack as ADO
Exercise: Bracket Matching
Exercise: Bracket Matching Algorithm
Exercise: Implement Bracket Matching Algorithm in C
Managing Abstract Data Types and Objects in C
Compilers
Summary
❖ COMP9024 24T1
Data Structures and Algorithms
Helen Paik
❖ Course Goals
COMP9021 …
COMP9024 …
gets you thinking like a computer scientist
knowing fundamental data structures/algorithms
able to reason about their applicability/effectiveness
able to analyse the efficiency of programs
able to code in C
Data structures
how to store data inside a computer for efficient use
Algorithms
step-by-step process for solving a problem (within finite amount of space and time)
❖ Pre-conditions
There are no prerequisites for this course.
However we will move at fast pace through the necessary programming fundamentals. You may find it helpful if you are able to:
❖ Post-conditions
At the end of this course you should be able to:
http://www.cse.unsw.edu.au/~cs9024
Bookmark the page ... a portal to all course related links (e.g., lecture content, forum, submitting assignments, viewing marks).
slides by Michael Thielscher (COMP9024 19T3,20T2), John Shepherd (COMP1927 16s2), Hui Wu (COMP9024 16s2) and Alan
Blair (COMP1917 14s2)
Robert Sedgewick's and Alistair Moffat's books, Goodrich and Tamassia's Java book, Skiena and Revilla's programming
challenges book
On Lectures: Tuesdays/Thursdays 2-4pm (recording release soon after the lecture via Echo360)
Weekly help sessions (K17, G05) - check the homepage
❖ Resources
Textbook is a "double-header"
❖ Resources (cont)
Supplementary textbook:
Alistair Moffat
Programming, Problem Solving, and Abstraction with C
Pearson Educational, Australia, Revised edition 2013, ISBN 978-1-48-601097-4
❖ Lectures
Lectures will:
present theory
demonstrate problem-solving methods
give practical demonstrations
❖ Weekly Practicals
In weeks 2-5, 7-10 :
Weekly Practicals (programming exercises) contribute 16% to overall mark ( 2 marks each x 8 weeks).
You may bring your own laptop to access materials or take notes
Important - tutorials are not marked; however, they provide an opportunity for a more intimate classroom experience where you can
interact more closely with the tutors and other students.
❖ Large Assignment
The large assignment gives you experience applying tools/techniques
(but to a larger programming problem than the homework)
The assignment will be released late Week 5 (or sometime in Week 6 ...) and is due in week 10.
The late penalty is a per-day mark reduction equal to 5% of the max assessment mark for up to 5 days.
For example, if an assignment that would receive an on-time mark of 8/12 is submitted 3 days late, it should receive a mark of 6.2/10.
❖ Plagiarism
Just Don't Do it
❖ Plagiarism (cont)
Examples of Plagiarism (student.unsw.edu.au/plagiarism):
1. Copying
2. Collusion
Any submission based on a work of another student, or a code repository (e.g., github), or generative AI tools (e.g., ChatGPT), or
contracted work is considered cheating.
Your submissions will be checked for and will be reported to the Academic Integrity Unit at UNSW.
❖ Mid-term Test
1-hour online test in Week 6 (Thursday, 2-3pm).
Format:
❖ Final Exam
2-hour torture written exam during the exam period.
Format:
Must score at least 25/60 in the final exam to pass the course.
❖ Assessment Summary
weekly_lab = mark for weekly program exercises (out of 2*8)
mid_term = mark for mid-term test (out of 12)
large_assn = mark for large assignment (out of 12)
exam = mark for final exam (out of 60)
❖ Summary
The goal is for you to become a better Computer Scientist
❖ C Programming Language
❖ Why C?
good example of an imperative language
gives the programmer great control
produces fast code
many libraries and resources
main language for writing operating systems and compilers; and commonly used for a variety of applications in industry (and
science)
❖ Brief History of C
C and UNIX operating system share a complex history …
. return 0;
. }
while (m != n) {
if (m > n) {
m = m-n;
} else {
n = n-m;
}
}
return m;
}
int main(void) {
printf("%d\n", f(30,18));
return 0;
}
insertionSort(A):
| Input array A[0..n-1] of n elements
|
| for all i=1..n-1 do
| | element=A[i], j=i-1
| | while j≥0 and A[j]>element do
| | A[j+1]=A[j]
| | j=j-1
| | end while
| | A[j+1]=element
| end for
gcc prog.c
To run the program, type:
./a.out
The default with gcc is not to give you any warnings about potential problems
Good practice is to be tough on yourself:
The -o option tells gcc to place the compiled object in the named file rather than a.out
%d decimal %f floating-point
%c character %s string
\n new line \" quotation mark
Examples:
num = 3;
printf("The cube of %d is %d.\n", num, num*num*num);
id = 'z';
num = 1234567;
printf("Your \"login ID\" will be in the form of %c%d.\n", id, num);
printf("%8.3f\n", 3.14159);
3.142
COMP9024 24T1 ♢ Elementary Data and Control Structures in C ♢ [33/103]
<< ∧ >>
❖ Algorithms in C
❖ Basic Elements
Algorithms are built using
assignments
conditionals
loops
function calls/return statements
❖ Assignments
In C, each statement is terminated by a semicolon ;
Curly brackets { } used to enclose statements in a block
Usual arithmetic operators: +, -, *, /, %
Usual assignment operators: =, +=, -=, *=, /=, %=
The operators ++ and -- can be used to increment a variable (add 1) or decrement a variable (subtract 1)
It is recommended to put the increment or decrement operator after the variable:
It is also possible (but NOT recommended) to put the operator before the variable:
❖ Assignments (cont)
C assignment statements are really expressions
v = getNextItem();
while (v != 0) {
process(v);
v = getNextItem();
}
is often written as
2.
a = 1; b = 5;
while ((a += 2) < b) {
b--;
}
1. a == 3, b == 3
2. a == 5, b == 4
❖ Conditionals
if (expression) {
some statements;
}
if (expression) {
some statements1;
} else {
some statements2;
}
some statements executed if, and only if, the evaluation of expression is non-zero
some statements1 executed when the evaluation of expression is non-zero
some statements2 executed when the evaluation of expression is zero
Statements can be single instructions or blocks enclosed in { }
❖ Conditionals (cont)
Indentation is very important in promoting the readability of the code
❖ Conditionals (cont)
Relational and logical operators
❖ Exercise: Conditionals
1. What is the output of the following program fragment?
Nay
2. No matter what the value of x, one of the conditions will be true (==1) and the other false (==0)
Hence the resulting value will be x == 1
❖ Loops
C has two different "while loop" constructs
The do .. while loop ensures the statements will be executed at least once
❖ Loops (cont)
The "for loop" in C
88
87
..
81
44
..
41
22
21
❖ Functions
Functions have the form
return-type function-name(parameters) {
declarations
statements
return …;
}
if return_type is void then the function does not return a value
if parameters is void then the function has no arguments
❖ Functions (cont)
When a function is called:
❖ Functions (cont)
When a return statement is executed, the function terminates:
return expression;
1. the returned expression will be evaluated
2. all local variables and parameters will be thrown away when the function terminates
3. the calling function is free to use the returned value, or to ignore it
Example:
The return statement can also be used to terminate a function of return-type void:
return;
❖ Data Structures in C
Variable declaration must specify a data type and a name; they can be initialised when they are declared:
float x;
char ch = 'A';
int j = i;
❖ Arrays
An array is
Examples:
❖ Arrays (cont)
Larger example:
#define MAX 20
fact[0] = 1;
for (i = 1; i < MAX; i++) {
fact[i] = i * fact[i-1];
}
❖ Sidetrack: C Style
We can define a symbolic constant at the top of the file
extern int
errno
;char
grrr
;main( r,
argv, argc ) int argc ,
r ; char *argv[];{int P( );
#define x int i, j,cc[4];printf(" choo choo\n" ) ;
x ;if (P( ! i ) | cc[ ! j ]
& P(j )>2 ? j : i ){* argv[i++ +!-i]
; for (i= 0;; i++ );
_exit(argv[argc- 2 / cc[1*argc]|-1<4 ] ) ;printf("%d",P(""));}}
P ( a ) char a ; { a ; while( a > " B "
/* - by E ricM arsh all- */); }
#define o define
#o ___o write
#o ooo (unsigned)
#o o_o_ 1
#o _o_ char
#o _oo goto
#o _oo_ read
#o o_o for
#o o_ main
#o o__ if
#o oo_ 0
#o _o(_,__,___)(void)___o(_,__,ooo(___))
#o __o (o_o_<<((o_o_<<(o_o_<<o_o_))+(o_o_<<o_o_)))+(o_o_<<(o_o_<<(o_o_<<o_o_)))
o_(){_o_ _=oo_,__,___,____[__o];_oo ______;_____:___=__o-o_o_; _______:
_o(o_o_,____,__=(_-o_o_<___?_-o_o_:___));o_o(;__;_o(o_o_,"\b",o_o_),__--);
_o(o_o_," ",o_o_);o__(--___)_oo _______;_o(o_o_,"\n",o_o_);______:o__(_=_oo_(
oo_,____,__o))_oo _____;}
❖ Strings
"String" is a special word for an array of characters
Example:
If a character array s[11] contains the string "hello", this is how it would look in memory:
0 1 2 3 4 5 6 7 8 9 10
---------------------------------------------
| h | e | l | l | o | \0| | | | | |
---------------------------------------------
❖ Array Initialisation
Arrays can be initialised by code, or you can specify an initial set of values in declaration.
Examples:
In the last case, C infers the array length (as if we declared vec[5]).
Array[2] = 32
String = "At"
...
char str[BUFSIZ];
int n;
Example:
❖ Multi-dimensional Arrays
Examples:
float q[][2] = {
{ 0.5, 2.7 },
{ 3.1, 0.1 }
};
❖ Structures
A structure
is a collection of variables, perhaps of different types, grouped together under a single name
helps to organise complicated data into manageable entities
exposes the connection between data within an entity
is defined using the struct keyword
Example:
typedef struct {
char name[30];
int zID;
} StudentT;
❖ Structures (cont)
One structure can be nested inside another:
typedef struct {
int day, month;
} DateT;
typedef struct {
int hour, minute;
} TimeT;
typedef struct {
char plate[7]; // e.g. "DSA42X"
double speed;
DateT d;
TimeT t;
} TicketT;
❖ Structures (cont)
Possible memory layout produced for TicketT object:
---------------------------------
| D | S | A | 4 | 2 | X | \0| | 7 bytes + 1 padding
---------------------------------
| 68.4 | 8 bytes
---------------------------------
| 2 | 6 | 8 bytes
---------------------------------
| 20 | 45 | 8 bytes
---------------------------------
Don't normally care about internal layout, since fields are accessed by name.
❖ Structures (cont)
Defining a structured data type itself does not allocate any memory
DateT christmas;
The components of the structure can be accessed using the "dot" operator
christmas.day = 25;
christmas.month = 12;
❖ Structures (cont)
With the above TicketT type, we declare and use variables as …
// Sample output:
//
// DSA42X 68.40 2/6 at 20:45
❖ Structures (cont)
A structure can be passed as a parameter to a function:
void print_date(DateT d) {
int is_winter(DateT d) {
❖ Data Abstraction
Operations:
Applications:
undo sequence in a text editor
bracket matching algorithm
…
❖ Stack vs Queue
Queue, aka FIFO data structure (first in, first out)
Applications:
❖ Stack as ADO
Interface (a file named Stack.h)
#define MAXITEMS 10
Note:
#include "Stack.h"
#include <assert.h>
1. (a+b) * c
2. a[i]+b[j]*c[k])
3. (a[i]+b[j])*c[k]
4. a(a+b]*c
5. void f(char a[], int n) {int i; for(i=0;i<n;i++) { a[i] = (a[i]*a[i])*(i+1); }}
6. a(a+b * c
1. balanced
2. not balanced (case 1: an opening bracket is missing)
3. balanced
4. not balanced (case 2: closing bracket doesn't match opening bracket)
5. balanced
6. not balanced (case 3: missing closing bracket)
bracketMatching(s):
| Input stream s of characters
| Output true if parentheses in s balanced, false otherwise
|
| for each ch in s do
| | if ch = open bracket then
| | push ch onto stack
| | else if ch = closing bracket then
| | | if stack is empty then
| | | return false // opening bracket missing (case 1)
| | | else
| | | pop top of stack
| | | if brackets do not match then
| | | return false // wrong closing bracket (case 2)
| | | end if
| | | end if
| | end if
| end for
| if stack is not empty then return false // some brackets unmatched (case 3)
| else return true
( [ { } ] )
#include "Stack.h"
Sidetrack: Character I/O Functions in C (requires <stdio.h>)
int getchar(void);
returns character read from standard input as an int, or returns EOF on end of file (keyboard: CTRL-D on Unix, CTRL-Z on
Windows)
❖ Compilers
Compilers are programs that
❖ Compilers (cont)
Compilation/linking with gcc
gcc -c Stack.c
produces Stack.o, from Stack.c and Stack.h
gcc -c brackets.c
produces brackets.o, from brackets.c and Stack.h
❖ Summary
Introduction to Algorithms and Data Structures
C programming language, compiling with gcc
Basic data types (char, int, float)
Basic programming constructs (if … else conditionals, while loops, for loops)
Basic data structures (atomic data types, arrays, structures)
Introduction to ADTs
Compilation