Week 1: Introduction

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [0/69]


❖ COMP9024 is a 2-in-1 course

It consists of two parts:

1. The C Programming Language
2. Data Structures and Algorithms

Together, we have Data Structures and Algorithms in C.

But we don’t have the luxury of learning the C programming language through traditional methods (like those used in COMP1511).

It means:

On one hand, you pay for one course but get the content of two.
On the other hand, COMP9024 has a steep learning curve.

Please work hard in Week 1 and harder after that.

To aid understanding, most of the algorithms (e.g., Bubble Sort) have been visualized in COMP9024.

A picture is more than a thousand words.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [1/69]


❖ How to use CSE VLAB

Please follow the steps in Introduction to CSE VLAB

Make sure that you know how to use CSE VLAB in Week 1.

Make sure that you understand the C program in Bubble Sort by the end of Week 2.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [2/69]


❖ COMP9024 24T3

Data Structures and Algorithms

[Diagram:Pic/COMP9024.png]

Changwei Zou


Web Site:   COMP9024 24T3

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [3/69]


❖ This term, your Teaching Team consists of ...

Lecturer in Charge:Changwei Zou
Course admin:Mingqin Yu
A team of tutors:... who are they?
Getting Help (technical/course contents):Use Help Sessions, or Course Forum
Email address to use (personal/non-technical issue):cs9024@cse.unsw.edu.au

When illness or circumstances beyond your control:Use UNSW Special Consideration

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [4/69]


❖ This term, your Teaching Team consists of ... (cont)

Tutors:John Chen
Deniz Dilsiz
Fangfei Fan
Ziming Gong
Janhavi Jain
Joffrey Ji
Leman Kirme
Ziting Li
Kisaru Liyanage
Thirasara Beruwawela Pathiranage
Adiyat Rahman
Nimish Ukey
Finn Xu
Oliver Xu
Sijia Xu
Mingqin Yu

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [5/69]


❖ Schedule (topics are not absolutely fixed ...)

WeekLecturesWeekly Prac/QuizWeekly TutAssignment
1Introduction, C language -- Large Assignment
2Dynamic data structures prac/quiz Tutorial|
3Analysis of algorithms prac/quiz Tutorial|
4Graph data structures prac/quiz Tutorial|
5Graph algorithms prac/quiz Tutorial|
6Mid-term test (online) (Thursday, 4pm-5pm) --|
7Search tree data structuresprac/quiz Tutorial|
8Search tree algorithms prac/quiz Tutorial|
9String algorithmsprac/quiz Tutorial|
10Randomised algorithms, Review prac/quiz Tutorial| due
Exam Week (Central)Final Exam (on campus) --

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [6/69]


❖ Assessment Summary

weekly_lab   = mark for weekly practicals/quizzes (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)


total = weekly_lab + mid_term + large_assn + exam

To pass the course, you must achieve:

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [7/69]


❖ Weekly Practical Exercises and Quizzes

In weeks 2-5, 7-10 :

Practical exercises are provided at the bottom of tutorial web pages (e.g., Tutorial in Week 2).

After completing each weekly practical exercise, please proceed to the weekly quiz on Moodle.

Weekly Quizzes (practical exercises) contribute 16% to overall mark ( 2 marks each x 8 weeks).

Do them yourself!   and   Don't fall behind!

Quizzes on Moodle

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [8/69]


❖ Large Assignment

The large assignment gives you experience applying tools/techniques
(but to a larger programming problem than weekly practical exercises)

The assignment will be carried out individually.

The assignment will be released in Week 1 and is due in week 10.

The assignment contributes 12% to overall mark.

Large Assignment on Github

Submit your answers in week 10 on Moodle

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [9/69]


❖ Mid-term Test

1-hour online test in Week 6 (Thursday, 4-5pm) on Moodle.

Format:

The mid-term test contributes 12% to overall mark.
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [10/69]


❖ Final Exam

2-hour written exam during the exam period.

Format:

The final exam contributes 60% to overall mark.

If you have any queries about your final exam on Inspera, please contact the UNSW Exams Centre on exams@unsw.edu.au

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [11/69]


❖ Complete weekly quizzes and the large assignment on time

Answers to the quizzes and the large assignment (assessed online via Moodle) will be released to students on completion.

For some assessment items, a late penalty may not be appropriate.

Such assessments will receive a mark of zero if not completed by the specified date. Examples include:

For more details, see COMP9024 Course Outline.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [12/69]


Start with reading, debugging and modifying a runnable program in COMP9024 on GitHub.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [13/69]


❖ Course Goals

COMP9021 …

COMP9024 … Data structures Algorithms
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [14/69]


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

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [15/69]


❖ Post-conditions

At the end of this course you should be able to:

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [16/69]


❖ Access to Course Material

Ideas for the COMP9024 material are drawn from

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [17/69]


❖ Resources

Textbook

[Diagram:Pic/AlgsP1-5.jpg]

Good books, useful beyond COMP9024 (but coding style …)

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [18/69]


❖ Resources (cont)

Supplementary textbook:

[Diagram:Pic/moffat.jpg]

Also, numerous online C resources are available.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [19/69]


❖ Lectures

Lectures will:

Lectures provide an alternative view to textbook

Lecture documents (e.g., programs, notes or slides) will be made available before lecture each week

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [20/69]


❖ Weekly Tutorials

The weekly tutorials/classes, with tutors, aims to:

You may bring your own laptop to access materials or take notes

Important - tutorials provide an opportunity for a more intimate classroom experience where you can interact more closely with the tutors and other students.

Tutorials on Github
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [21/69]


❖ Plagiarism

[Diagram:Pic/plagiarism.jpg]

Just Don't Do it

We get very annoyed by people who plagiarise.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [22/69]


❖ Plagiarism (cont)

Examples of Plagiarism (student.unsw.edu.au/plagiarism):

  1. Copying

    Using same or similar idea without acknowledging the source
    This includes copying ideas from a website, internet

  2. Collusion

    Presenting work as independent when produced in collusion with others
    This includes students providing their work to another student

    • which includes using any form of publicly readable code repository

Your submissions will be checked for and will be reported to the Academic Integrity Unit at UNSW.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [23/69]


❖ Summary

The goal is for you to become a better programmer

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [24/69]


❖ C Programming Language

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [25/69]


❖ Why C?

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [26/69]


❖ Brief History of C

C and UNIX operating system share a complex history …

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [27/69]


❖ Basic Structure of a C Program

// include files
// global definitions

// function definitions
function_type f(arguments) {

   // local variables

   // body of function

  return …;
}

.
.

                                       

.
.
.
.
.

// main function
int main(arguments) {

   // local variables

   // body of main function

   return 0;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [28/69]


❖ Compiling with gcc

C source code:   prog.c
prog   (executable program)

To compile a program prog.c, you type the following:

gcc prog.c -o prog

To report all warnings, type:

gcc -Wall prog.c -o prog

To run the program, type:

./prog

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [29/69]


❖ Sidetrack: Printing Variable Values with printf()

Formatted output written to standard output (e.g. screen)

int printf(const char *formatString, ...);

formatString can use the following placeholders:

%d  decimal       %f  floating-point
%c  character       %s  string
\n  new line       \"  quotation mark

Examples:

int num = 3;
printf("The cube of %d is %d.\n", num, num*num*num);

The cube of 3 is 27.

char ch  = 'z';
int num = 1234567;
printf("Your \"login ID\" will be in the form of %c%d.\n", ch, num);

Your "login ID" will be in the form of z1234567.

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [30/69]


❖ Algorithms in C

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [31/69]


❖ Basic Elements

Algorithms are built using

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [32/69]


❖ Assignments

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [33/69]


❖ Assignments (cont)

Example: The pattern

v = getNextItem();
while (v != 0) {
   process(v);
   v = getNextItem();
}

can be written as

while ((v = getNextItem()) != 0) {
   process(v);
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [34/69]


❖ Conditionals

if (expression) {
   some statements;
}

if (expression) {
   some statements1;
} else {
   some statements2;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [35/69]


❖ Conditionals (cont)

Indentation is very important in promoting the readability of the code

Each logical block of code is indented:

// Style 1    
if (x)
{
   statements;
}

           

// Style 2 (my preference)
if (x) {
   statements;
}

           

// Preferred else-if style
if (expression1) {
   statements1;
} else if (exp2) {
   statements2;
} else if (exp3) {
   statements3;
} else {
   statements4;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [36/69]


❖ Conditionals (cont)

Relational and logical operators

a > ba greater than b
a >= ba greater than or equal to b
a < ba less than b
a <= ba less than or equal to b
a == ba equal to b
a != ba not equal to b
a && ba logical and b
a || ba logical or b
! alogical not a

A relational or logical expression evaluates to 1 if true, and to 0 if false

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [37/69]


❖ Loops

C has two different "while loop" constructs

// while loop         
while (expression) {
    some statements; 
}

               

// do .. while loop
do {
   some statements;   
} while (expression);

The  do .. while  loop ensures the statements will be executed at least once

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [38/69]


❖ Loops (cont)

The "for loop" in C

for (expr1; expr2; expr3) {
   some statements;
}

 
Example:    

for (i = 1; i < 10; i++) {
   printf("%d %d\n", i, i * i);
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [39/69]


❖ Functions

Functions have the form

return-type function-name(parameters) {

    declarations

    statements

    return …;
}

int square(int n) {
   int s;
   s = n * n;
   return s;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [40/69]


❖ Functions (cont)

When a function is called:

  1. memory is allocated for its parameters and local variables
  2. the parameter expressions in the calling function are evaluated
  3. C uses "call-by-value" parameter passing …
    • the function works only on its own local copies of the parameters, not the ones in the calling function
  4. local variables need to be assigned before they are used   (otherwise they will have "garbage" values)
  5. function code is executed, until the first return statement is reached
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [41/69]


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



int add(int m, int n) {
    return m + n;    
}

The return statement can also be used to terminate a function of return-type void:

return;

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [42/69]


❖ Data Structures in C

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [43/69]


❖ Basic Data Types

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [44/69]


❖ Aggregate Data Types

Families of aggregate data types:

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [45/69]


❖ Arrays

An array is

Examples:

int  a[20];    // array of 20 integer values/variables
char b[10];    // array of 10 character values/variables

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [46/69]


❖ Arrays (cont)

Larger example:

#define MAX 20

int numbers[MAX];   // array of 20 integer values


for (int i = 0; i < MAX; i++) {
   numbers[i] = i * i;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [47/69]


❖ Macros in C

We can define a macro in C (i.e., a symbolic constant)

#define SPEED_OF_LIGHT 299792458.0
#define ERROR_MESSAGE "Out of memory.\n"

Symbolic constants make the code easier to understand and maintain

#define NAME replacement_text

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [48/69]


❖ Coding Style

UNSW Computing provides a style guide for C programs:

C Coding Style Guide    (http://wiki.cse.unsw.edu.au/info/CoreCourses/StyleGuide)


Not strictly mandatory for COMP9024, but very useful guideline

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [49/69]


❖ Strings

"String" is a special word for an array of characters

Example:

If a character array t[6] contains the string "hello", this is how it would look in memory:

char t[6] = "hello";

 
-------------------------
| h | e | l | l | o | \0| 
-------------------------
  0   1   2   3   4   5  

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [50/69]


❖ Array Initialisation

Arrays can be initialised by code, or you can specify an initial set of values in declaration.

Examples:

char s[6]   = {'h', 'e', 'l', 'l', 'o', '\0'};

char t[6]   = "hello";

int arr[5]   = {5, 4, 3, 2, 1};

int vec[]   = {5, 4, 3, 2, 1};

In the last case, C infers the array length   (as if we declared vec[5]).

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [51/69]


❖ Sidetrack: Reading Variable Values with scanf()

Formatted input read from standard input (e.g. keyboard)

scanf(format-string, expr1, expr2, …);

Example: InputOutput.c


#include <stdio.h>   //  printf() and scanf()
int main(void) {
    int number;
    printf("Enter an integer: \n");
    scanf("%d", &number);
    printf("You entered: %d \n", number);
    return 0;
}


$ gcc InputOutput.c -o InputOutput
$ ./InputOutput 
Enter an integer: 
30
You entered: 30 

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [52/69]


❖ Arrays and Functions

When an array is passed as a parameter to a function

Example:

int total;
int vec[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
…
total = sum(vec);

Within the function …

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [53/69]


❖ Arrays and Functions (cont)

Since functions do not know how large an array is:

So, the previous example would be more likely done as:

#define N 10
int total;
int vec[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
…
total = sum(vec,N);

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [54/69]


❖ Exercise: Arrays and Functions

Implement a function that sums up all elements in an array.

Use the prototype

int sum(int[], int)

or

int sum(int *, int)

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [55/69]


int sum(int vec[], int dim) { 
   int total = 0;

   for (int i = 0; i < dim; i++) {
      total += vec[i];
   }
   return total;
}

or

int sum(int *vec, int dim) { 
   int total = 0;

   for (int i = 0; i < dim; i++) {
      total += vec[i];
   }
   return total;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [56/69]


❖ Multi-dimensional Arrays

Examples:

[Diagram:Pic/matrices.png]


Note:   q[0][1]==2.7    r[1][3]==8

Multi-dimensional arrays can also be initialised (must provide # of columns):

float q[][2] = {
   { 0.5, 2.7 },
   { 3.1, 0.1 }
};

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [57/69]


❖ Sidetrack: Defining New Data Types

C allows us to define new data type (names) via typedef:

typedef ExistingDataType NewTypeName;

Examples:

typedef float Temperature;

typedef int Matrix[20][20];

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [58/69]


❖ Sidetrack: Defining New Data Types (cont)

Reasons to use typedef:

typedef float Real;
Real complex_calculation(Real a, Real b) {
	Real c = log(a+b); … return c;
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [59/69]


❖ Structures

A structure

Example:

typedef struct {
   char name[32];
   int  zID;
} StudentT;

StudentT neo;

or

struct Student {
   char name[32];
   int  zID;
};

struct Student neo;

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [60/69]


❖ Structures (cont)

One structure can be nested inside another:

typedef struct {
   int day;
   int month;
} DateT;

typedef struct {
   int hour, minute;
} TimeT;

typedef struct {
   long tid;   // ticket id
   DateT  d;
   TimeT  t;
} TicketT;

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [61/69]


❖ Structures (cont)

A structure can be passed as a parameter to a function:

void print_date(DateT d) {
   printf("%d/%d\n", d.day, d.month);
}

int is_winter(DateT d) {
   return ( (d.month >= 6) && (d.month <= 8) );
}

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [62/69]


❖ Data Abstraction

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [63/69]


❖ Abstract Data Types

A data type is …

  • a set of values   (atomic or structured values)     e.g. integer stacks
  • a collection of operations on those values   e.g. push, pop, isEmpty?
An abstract data type
  • is a logical description of how we view the data and operations
  • without regard to how they will be implemented
  • creates an encapsulation around the data
  • is a form of information hiding

[Diagram:Pic/ADT.png]

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [64/69]


❖ Abstract Data Types (cont)

Users of the ADT see only the interface

Builders of the ADT provide an implementation

ADT interface provides

  • a user-view of the data structure
  • function signatures (prototypes) for all operations
  • semantics of operations (via documentation)
  • ⇒  a "contract" between ADT and its clients

   // Stack.h
   struct Stack;
   // Create a stack
   struct Stack *CreateStack(void);
   ...      

ADT implementation gives

  • concrete definition of the data structures
  • function implementations for all operations

   // Stack.c
   struct Stack {
      ...
   };   
   struct Stack *CreateStack(void) {      
      ...       
   }   

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [65/69]


❖ Abstract Data Types (cont)

ADT interfaces are opaque

  • clients cannot see the implementation via the interface
ADTs are important because …
  • facilitate decomposition of complex programs
  • make implementation changes invisible to clients
  • improve readability and structuring of software
  • allow for reuse of modules in other systems
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [66/69]


❖ Stack vs Queue

Stack, aka FILO data structure (first in, last out)


   Insert and delete are called push and pop

Applications of Stack:

Queue, aka FIFO data structure (first in, first out)


   Insert and delete are called enqueue and dequeue

Applications of Queue:

  • people queueing to go onto a bus
  • breadth first search in a graph
  • web page requests arriving at a web server
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [67/69]


❖ Compilers

Compilers are programs that

  • convert program source code to executable form
  • "executable" might be machine code or bytecode
The Gnu C compiler toolchain (gcc test.c -o test)
  • applies source-to-source transformation (Preprocessor)

    
    gcc -E test.c -o test.i
    

  • compiles source code to produce assembly code (Compiler)

    
    gcc -c -S test.i -o test.s
    

  • assembles assembly code to produce object files (Assember)

    
    gcc -c test.s -o test.o
    

  • links object files and libraries to produce executables (Linker)

    
    gcc test.o -o test
    

[Diagram:Pic/FourSteps.png]

COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [68/69]


❖ Summary

  • Introduction to Algorithms and Data Structures
  • C programming language, compiling with gcc
    • Basic data types (char, short, int, long, float, double)
    • Basic programming constructs (ifelse conditionals, while loops, for loops)
    • Basic data structures (atomic data types, arrays, structures)
  • Introduction to ADTs
  • Compilation
COMP9024 24T3 ♢ Elementary Data and Control Structures in C ♢ [69/69]



Produced: 10 Sep 2024