COMP9024 ♢ Week 01a ♢Introduction - Elementary Data and Control Structures in C ♢ (22T0)

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [0/104]
❖ COMP9024 22T0

Data Structures and Algorithms

[Diagram:Pic/COMP9024.png]

Ashesh Mahidadia


Web Site:   https://webcms3.cse.unsw.edu.au/COMP9024/22T0/

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [1/104]
❖ Course Staff

Convenor:Ashesh Mahidadia
Email:ashesh@cse.unsw.edu.au
Research:Machine Learning, Knowledge Based Systems, Artificial Intelligence


Admin and Tutor:Daria Schumm
Course Email:cs9024@cse.unsw.edu.au

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [2/104]
❖ Course Goals

COMP9021 …

COMP9024 …
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [3/104]
❖ ... Course Goals

COMP9021 …

[Diagram:Pic/children.jpg]

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [4/104]
❖ ... Course Goals

COMP9024 …
 

[Diagram:Pic/hard-work.jpg]

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [5/104]
❖ Pre-conditions

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [6/104]
❖ Post-conditions

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [7/104]
❖ COMP9024 Themes

Data structures

Algorithms Major themes …
  1. Data structures, e.g. for graphs, trees
  2. A variety of algorithms, e.g. on graphs, trees, strings
  3. Analysis of algorithms
For data types: alternative data structures and implementation of operations

For algorithms: complexity analysis

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [8/104]
❖ Access to Course Material

All course information is placed on the main course website:

Need to login to access material, submit homework and assignment, post on the forum, view your marks

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [9/104]
❖ Schedule

Please note that the following schedule is subject to change.

Lecture TopicWeek(s)
Elementary data structures and algorithms in CWeek 1
Analysis of algorithmsWeek 1-2
Dynamic data structuresWeek 2
Search tree data structures and algorithmsWeek 2-3
Graph data structures and algorithms Week 3-4
Text Processing algorithmsWeek 4-5
Course reviewWeek 5

Assignment (30%):
Available on Wednesday of Week-01 (05/Jan/2022), due at 10am Tuesday of Week-05 (01/Feb/2021).

Quizzes (20%) :
Quiz-1 (5%): available on Thursday of Week-01, due on Tuesday of Week-02.
Quiz-2 (5%): available on Thursday of Week-02, due on Tuesday of Week-03.
Quiz-3 (5%): available on Thursday of Week-03, due on Tuesday of Week-04.
Quiz-4 (5%): available on Thursday of Week-04, due on Tuesday of Week-05.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [10/104]
❖ Credits for Material

Always give credit when you use someone else's work.

The lecture slides are prepared by Michael Thielscher, and ideas for the COMP9024 material are drawn from

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [11/104]
❖ Resources

Textbook is a "double-header"

[Diagram:Pic/AlgsP1-5.jpg]

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [12/104]
❖ ... Resources

Supplementary textbook:

[Diagram:Pic/moffat.jpg]

Also, numerous online C resources are available.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [13/104]
❖ Lectures

Lectures will:

Lectures provide an alternative view to textbook

Lecture slides will be made available before lecture

Feel free to ask questions, but No Idle Chatting

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [14/104]
❖ Problem Sets

The weekly homework aims to:

Problem sets available on web at the time of the lecture

Sample solutions will be posted in the following week

Do them yourself!   and   Don't fall behind!

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [15/104]
❖ Assignment

The assignment gives you experience applying tools/techniques
(but to a larger programming problem than the homework)

The assignment will be carried out individually.

The assignment will be released in Week-1.

The assignment contributes 30% to overall mark.

10% penalty will be applied to the maximum mark for every 24 hours late after the deadline.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [16/104]
❖ ... Assignment

Advice on doing assignments:

They always take longer than you expect.

Don't leave them to the last minute.

Organising your time no late penalty.

If you do leave them to the last minute:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [17/104]
❖ Plagiarism

[Diagram:Pic/plagiarism.jpg]

Just Don't Do it

We get very annoyed by people who plagiarise.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [18/104]
❖ ... Plagiarism

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

Plagiarism will be checked for and punished  (0 marks for assignment or, in severe cases/repeat offenders, 0 marks for course)

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [19/104]
❖ Help Sessions

The help Sessions:

Times - to be published later.

Attendance is entirely voluntary

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [20/104]
❖ Final Exam

3-hour Final exam during the exam period.

Format:

The final exam contributes 50% to overall mark.

Must score at least 25/50 in the final exam to pass the course.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [21/104]
❖ ... Final Exam

How to pass the Final Exam:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [22/104]
❖ Assessment Summary

Read the course outline at Assessment .

Alternatively, go to https://webcms3.cse.unsw.edu.au/COMP9024/22T0/outline#assessment .

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [23/104]
❖ Summary

The goal is for you to become a better Computer Scientist

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [24/104]
❖ C Programming Language

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [25/104]
❖ Why C?

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [26/104]
❖ Brief History of C

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [27/104]
❖ ... Brief History of C

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [28/104]
❖ 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 (22T0) ♢ Week 01a ♢ Introduction ♢ [29/104]
❖ Exercise : What does this program compute?

#include <stdio.h>

int f(int m, int n) {

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [30/104]
❖ Example: Insertion Sort in C

Reminder — Insertion Sort algorithm:

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [31/104]
❖ ... Example: Insertion Sort in C


#include <stdio.h> // include standard I/O library defs and functions

#define SIZE 6     // define a symbolic constant

void insertionSort(int array[], int n) {  // function headers must provide types
   int i;                                 // each variable must have a type
   for (i = 1; i < n; i++) {              // for-loop syntax
      int element = array[i];                                                    
      int j = i-1;
      while (j >= 0 && array[j] > element) {  // logical AND
         array[j+1] = array[j];
         j--;                                 // abbreviated assignment j=j-1 
      }
      array[j+1] = element;                   // statements terminated by ;
   }                                          // code blocks enclosed in { } 
}

int main(void) {                              // main: program starts here
   int numbers[SIZE] = { 3, 6, 5, 2, 4, 1 };  /* array declaration
                                                 and initialisation */
   int i;
   insertionSort(numbers, SIZE);
   for (i = 0; i < SIZE; i++)
      printf("%d\n", numbers[i]);             // printf defined in <stdio>

   return 0;           // return program status (here: no error) to environment
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [32/104]
❖ Compiling with gcc

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

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

gcc prog.c

To run the program, type:

./a.out

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [33/104]
❖ ... Compiling with gcc

Command line options:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [34/104]
❖ Algorithms in C

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [35/104]
❖ Basic Elements

Algorithms are built using

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [36/104]
❖ Assignments

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [37/104]
❖ ... Assignments

C assignment statements are really expressions

Frequently, assignment is used in loop continuation tests Example: The pattern

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

is often written as

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [38/104]
❖ Exercise : What are the final values of a and b?

  1. 
    a = 1; b = 5;
    while (a < b) {
       a++;
       b--;
    }
    

  2. 
    a = 1; b = 5;
    while ((a += 2) < b) {
       b--;
    }
    

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [39/104]
  1. a == 3, b == 3
  2. a == 5, b == 4
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [40/104]
❖ Conditionals

if (expression) {
   some statements;
}

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [41/104]
❖ ... Conditionals

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 (22T0) ♢ Week 01a ♢ Introduction ♢ [42/104]
❖ ... Conditionals

Relational and logical operators

a > ba greater than b
a >= ba greater than or equal b
a < ba less than b
a <= ba less than or equal 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 (22T0) ♢ Week 01a ♢ Introduction ♢ [43/104]
❖ Exercise : Conditionals

  1. What is the output of the following program fragment?

    if ((x > y) && !(y-x <= 0)) {
        printf("Aye\n");
    } else {
        printf("Nay\n");
    }
    

  2. What is the resulting value of x after the following assignment?

    x = (x >= 0) + (x < 0);
    

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [44/104]
  1. The condition is unsatisfiable, hence the output will always be

    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
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [45/104]
❖ Sidetrack: Printing Variable Values with printf()

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

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

format-string can use the following placeholders:

%d  decimal       %f  fixed-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);

The cube of 3 is 27.

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

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [46/104]
❖ 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 (22T0) ♢ Week 01a ♢ Introduction ♢ [47/104]
❖ ... Loops

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 (22T0) ♢ Week 01a ♢ Introduction ♢ [48/104]
❖ Exercise : What is the output of this program?

int i, j;
for (i = 8; i > 1; i /= 2) {
    for (j = i; j >= 1; j--) {
        printf("%d%d\n", i, j);
    }
    putchar('\n');
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [49/104]

88
87
..
81

44
..
41

22
21


COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [50/104]
❖ Functions

Functions have the form

return-type function-name(parameters) {

    declarations

    statements

    return …;
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [51/104]
❖ ... Functions

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 (22T0) ♢ Week 01a ♢ Introduction ♢ [52/104]
❖ ... Functions

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:


// Euclid's gcd algorithm (recursive version)
int euclid_gcd(int m, int n) {
    if (n == 0) {
        return m;
    } else {
        return euclid_gcd(n, m % n);
    }
}

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

return;

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [53/104]
❖ Data Structures in C

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [54/104]
❖ Basic Data Types

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [55/104]
❖ Aggregate Data Types

Families of aggregate data types:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [56/104]
❖ Arrays

An array is

Examples:

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [57/104]
❖ ... Arrays

Larger example:

#define MAX 20

int i;           // integer value used as index
int fact[MAX];   // array of 20 integer values

fact[0] = 1;
for (i = 1; i < MAX; i++) {
    fact[i] = i * fact[i-1];
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [58/104]
❖ Sidetrack: C Style

We can define a symbolic constant at the top of the file

#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 (22T0) ♢ Week 01a ♢ Introduction ♢ [59/104]
❖ ... Sidetrack: C 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

Style considerations that do matter for your COMP9024 assignments:
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [60/104]
❖ ... Sidetrack: C Style

C has a reputation for allowing obscure code, leading to …

The International Obfuscated C Code Contest

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [61/104]
❖ ... Sidetrack: C Style

Most artistic code (Eric Marshall, 1986)


                                                   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-      */);    }

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [62/104]
❖ ... Sidetrack: C Style

Just plain obscure (Ed Lycklama, 1985)


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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [63/104]
❖ 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|   |   |   |   |   |
---------------------------------------------

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [64/104]
❖ 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 fib[20] = {1, 1};

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

In the third case, fib[0] == fib[1] == 1 while the initial values fib[2] .. fib[19] are undefined.

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [65/104]
❖ Exercise : What is the output of this program?

 1  #include <stdio.h>
 2
 3  int main(void) {
 4     int arr[3] = {10,10,10};
 5     char str[] = "Art";
 6     int i;
 7
 8     for (i = 1; i < 3; i++) {
 9        arr[i] = arr[i-1] + arr[i] + 1;
10        str[i] = str[i+1];
11     }
12     printf("Array[2] = %d\n", arr[2]);
13     printf("String = \"%s\"\n", str);
14     return 0;
15  }

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [66/104]

Array[2] = 32
String = "At"

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [67/104]
❖ Sidetrack: Reading Variable Values with scanf() and atoi()

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

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

Converting string into integer

int value = atoi(string);

Example:


#include <stdio.h>   // includes definition of BUFSIZ (usually =512) and scanf()
#include <stdlib.h>  // includes definition of atoi()

...

char str[BUFSIZ];
int n;

printf("Enter a string: ");
scanf("%s", str);
n = atoi(str);
printf("You entered: \"%s\". This converts to integer %d.\n", str, n);


Enter a string: 9024
You entered: "9024". This converts to integer 9024.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [68/104]
❖ Arrays and Functions

When an array is passed as a parameter to a function

Example:

int total, vec[20];
…
total = sum(vec);

Within the function …

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [69/104]
❖ ... Arrays and Functions

Since functions do not know how large an array is:

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

int total, vec[20];
…
total = sum(vec,20);

Also, since the function doesn't know the array size, it can't check whether we've written an invalid subscript (e.g. in the above example 100 or 20).

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [70/104]
❖ Exercise : Arrays and Functions

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

Use the prototype

int sum(int[], int)

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [71/104]

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

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [72/104]
❖ Multi-dimensional Arrays

Examples:

[Diagram:Pic/matrices.png]


Note:   q[0][1]==2.7    r[1][3]==8    q[1]=={3.1,0.1}

Multi-dimensional arrays can also be initialised:

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [73/104]
❖ 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 (22T0) ♢ Week 01a ♢ Introduction ♢ [74/104]
❖ ... Sidetrack: Defining New Data Types

Reasons to use typedef:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [75/104]
❖ Structures

A structure

Example:

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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [76/104]
❖ ... Structures

One structure can be nested inside another:

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

typedef struct {
	int hour, minute;
} TimeT;

typedef struct {
	char   plate[7];   // e.g. "DSA42X"
	double speed;
        DateT  d;
	TimeT  t;
} TicketT;

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [77/104]
❖ ... Structures

Possible memory layout produced for TicketT object:

---------------------------------
| D | S | A | 4 | 2 | X | \0|   |        7 bytes + 1 padding
---------------------------------
|                          68.4 |                    8 bytes
-------------------------------------------------
|            27 |             7 |           2019|   12 bytes
-------------------------------------------------
|            20 |            45 |                    8 bytes
---------------------------------

 

Note: padding is needed to ensure that plate lies on a 4-byte boundary.

Don't normally care about internal layout, since fields are accessed by name.

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [78/104]
❖ ... Structures

Defining a structured data type itself does not allocate any memory

We need to declare a variable in order to allocate memory

DateT christmas;

The components of the structure can be accessed using the "dot" operator

christmas.day   =   25;
christmas.month =   12;
christmas.year  = 2019;

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [79/104]
❖ ... Structures

With the above TicketT type, we declare and use variables as …


#define NUM_TICKETS 1500

typedef struct {…} TicketT;

TicketT tickets[NUM_TICKETS];  // array of structs

// Print all speeding tickets in a readable format
for (i = 0; i < NUM_TICKETS; i++) {
    printf("%s %6.3f %d-%d-%d at %d:%d\n", tickets[i].plate,
					   tickets[i].speed,
					   tickets[i].d.day,
					   tickets[i].d.month,
					   tickets[i].d.year,
					   tickets[i].t.hour,
					   tickets[i].t.minute);
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [80/104]
❖ ... Structures

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

void print_date(DateT d) {

	printf("%d-%d-%d\n", d.day, d.month, d.year);
}

int is_leap_year(DateT d) {

	return ( ((d.year%4 == 0) && (d.year%100 != 0))
        	 || (d.year%400 == 0) );
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [81/104]
❖ Data Abstraction

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [82/104]
❖ Abstract Data Types

A data type is …

An abstract data type

[Diagram:Pic/ADT.png]

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [83/104]
❖ ... Abstract Data Types

Users of the ADT see only the interface

Builders of the ADT provide an implementation

ADT interface provides

ADT implementation gives
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [84/104]
❖ ... Abstract Data Types

ADT interfaces are opaque

ADTs are important because …
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [85/104]
❖ ... Abstract Data Types

For a given data type

For a given operation and data representation Generally,
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [86/104]
❖ ADOs and ADTs

We want to distinguish …

Warning: Sedgewick's first few examples are ADOs, not ADTs.
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [87/104]
❖ Example: Abstract Stack Data Object

Stack, aka pushdown stack or LIFO data structure

Assume (for the time being) stacks of char values

Operations:

Applications:
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [88/104]
❖ ... Example: Abstract Stack Data Object

Example of use:

Stack  Operation  Return value
?  create  -
-  isempty  true
-  push a  -
a  push b  -
a b  push c  -
a b c  pop  c
a b  isempty  false
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [89/104]
❖ Exercise : Stack vs Queue

Consider the previous example but with a queue instead of a stack.

Which element would have been taken out ("dequeued") first?

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [90/104]

a
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [91/104]
❖ Stack as ADO

Interface (a file named Stack.h)

// Stack ADO header file

#define MAXITEMS 10

void StackInit();      // set up empty stack
int  StackIsEmpty();   // check whether stack is empty
void StackPush(char);  // insert char on top of stack
char StackPop();       // remove char from top of stack

Note:

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [92/104]
❖ ... Stack as ADO

Implementation may use the following data structure:

[Diagram:Pic/stack.png]

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [93/104]
❖ ... Stack as ADO

Implementation (in a file named Stack.c):


#include "Stack.h"
#include <assert.h>

// define the Data Structure
typedef struct {
   char item[MAXITEMS];
   int  top;
} stackRep;

// define the Data Object
static stackRep stackObject;

// set up empty stack
void StackInit() {
   stackObject.top = -1;
}

// check whether stack is empty
int StackIsEmpty() {
   return (stackObject.top < 0);
}






// insert char on top of stack
void StackPush(char ch) {
   assert(stackObject.top < MAXITEMS-1);
   stackObject.top++;
   int i = stackObject.top;
   stackObject.item[i] = ch;
}

// remove char from top of stack
char StackPop() {
   assert(stackObject.top > -1);
   int i = stackObject.top;
   char ch = stackObject.item[i];
   stackObject.top--;
   return ch;
}


COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [94/104]
❖ Exercise : Bracket Matching

Bracket matching … check whether all opening brackets such as '(', '[', '{' have matching closing brackets ')', ']', '}'

Which of the following expressions are balanced?

  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
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [95/104]
  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)
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [96/104]
❖ ... Stack as ADO

Bracket matching algorithm, to be implemented as a client for Stack ADO:


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

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [97/104]
❖ ... Stack as ADO

Execution trace of client on sample input:

( [ { } ] )

Next char  Stack  Check
- empty -
( ( -
[ ( [ -
{ ( [ { -
} ( [ {  vs  }   ✓
] ( [  vs  ]   ✓
) empty (  vs  )   ✓
eof empty -
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [98/104]
❖ Exercise : Bracket Matching Algorithm

Trace the algorithm on the input

void f(char a[], int n) {
   int i;
   for(i=0;i<n;i++) { a[i] = a[i]*a[i])*(i+1); }
}

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [99/104]
Next bracket  Stack  Check
start empty -
( ( -
[ ( [ -
] ( 
) empty 
{ { -
( { ( -
) { 
{ { { -
[ { { [ -
] { {  
[ { { [ -
] { {  
[ { { [ -
] { {  
) { false
COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [100/104]
❖ Exercise : Implement Bracket Matching Algorithm in C

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [101/104]
❖ Compilers

Compilers are programs that

The Gnu C compiler (gcc)

[Diagram:Pic/gcc.png]

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [102/104]
❖ ... Compilers

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

gcc -o rbt brackets.o Stack.o
links brackets.o, Stack.o and libraries
producing executable program called rbt

Note that stdio,assert included implicitly.

gcc is a multi-purpose tool

COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [103/104]
❖ Summary


COMP9024 (22T0) ♢ Week 01a ♢ Introduction ♢ [104/104]


Produced: 20 Dec 2021