Week 01a: Introduction - Elementary Data and Control Structures in C


COMP9024 19T01/88

Data Structures and Algorithms

[Diagram:Pic/COMP9024-small.png]

Ashesh Mahidadia


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


Course Convenor2/88

Name:Ashesh Mahidadia
Email:ashesh@cse.unsw.edu.au
Consults:See "Help Labs" (next slide),  Forum
Research:Artificial Intelligence, Machine Learning, Knowedge Based Systems, Intelligent Systems


Consultations/Help Labs3/88

The help lab:

Location: TBA.

Times:


Course Goals4/88

COMP9021 …

COMP9024 …


... Course Goals5/88

COMP9021 …

[Diagram:Pic/children-small.jpg]


... Course Goals6/88

COMP9024 …
 

[Diagram:Pic/military-small.jpg]


... Course Goals7/88

COMP9024 …
 

[Diagram:Pic/hard-work-small.png]


Pre-conditions8/88

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


Post-conditions9/88

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


COMP9024 Themes10/88

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


Access to Course Material11/88

All course information is placed on the course website:

Slides/Problem Sets are publicly readable.

If you want to post/submit, you need to login.


Schedule and Assessments12/88

See the course outline,


Credits for Material13/88

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

Ideas for the COMP9024 material are drawn from


Resources14/88

Textbook is a "double-header"

       

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


... Resources15/88

Supplementary textbook:

[Diagram:Pic/moffat-small.jpg]

Also, numerous online C resources are available.


Lectures16/88

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


Problem Sets17/88

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!


Assignments18/88

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

The assignments will be carried out individually.

Both assignments will have a deadline at 11:59pm.

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

The two assignments contribute 10% + 15% to overall mark.


... Assignments19/88

Advice on doing the 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:


Plagiarism20/88

[Diagram:Pic/noose1-small.jpg]

Just Don't Do it

We get very annoyed by people who plagiarise.

Plagiarism will be checked for and punished.


Consultations/Help Labs21/88

The help lab:

Location: TBA.

Times:


Exams22/88


... Exams23/88

How to pass the Exams:


Assessment Summary24/88

ass1  = mark for assignment 1   (out of 10)
ass2  = mark for assignment 2   (out of 15)
mid   = mark for mid-term exam  (out of 15)
final = mark for final exam     (out of 60)

if (mid+final >= 38)
   total = ass1 + ass2 + mid + final
else
   total = (mid+final) / 0.75;

To pass the course, you must achieve:


Summary25/88

The goal is for you to become a better Computer Scientist


C Programming Language


Why C?27/88


Brief History of C28/88


... Brief History of C29/88


Basic Structure of a C Program30/88

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


Exercise #1: What does this program compute?31/88

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


Example: Insertion Sort in C32/88

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 ∧ A[j]>element do
|  |     A[j+1]=A[j]
|  |     j=j-1
|  |  end while
|  |  A[j+1]=element
|  end for


... Example: Insertion Sort in C33/88


#include <stdio.h>

#define SIZE 6

void insertionSort(int array[], int n) {
   int i;
   for (i = 1; i < n; i++) {
      int element = array[i];                 // for this element ...
      int j = i-1;
      while (j >= 0 && array[j] > element) {  // ... work down the ordered list       
         array[j+1] = array[j];               // ... moving elements up
         j--;
      }
      array[j+1] = element;                   // and insert in correct position
   }
}

int main(void) {
   int numbers[SIZE] = { 3, 6, 5, 2, 4, 1 };
   int i;
   
   insertionSort(numbers, SIZE);
   for (i = 0; i < SIZE; i++)
      printf("%d\n", numbers[i]);

   return 0;
}


... Example: Insertion Sort in C34/88


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


Compiling with gcc35/88

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

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

prompt$ gcc prog.c

To run the program, type:

prompt$ ./a.out


... Compiling with gcc36/88

Command line options:


Algorithms in C


Basic Elements38/88

Algorithms are built using


Assignments39/88


... Assignments40/88

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

can be written as

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


Exercise #2: What are the final values of a and b?41/88

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

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


  1. a == 3, b == 3    a == 4, b == 4
  2. a == 5, b == 4


Conditionals43/88

if (expression) {
   some statements;
}

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


... Conditionals44/88

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 (preferred)
if (x) {
   statements;
}

               

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


... Conditionals45/88

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


Exercise #3: Conditionals46/88

  1. What is the output of the following program?

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


  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


Sidetrack: Printing Variable Values with printf()48/88

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.

char id  = 'z';
int  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.


Loops49/88

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


... Loops50/88

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


Exercise #4: What is the output of this program?51/88

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


88
87
..
81

43
..
41

22
21


Functions53/88

Functions have the form

return-type function-name(parameters) {

    declarations

    statements

    return …;
}


... Functions54/88

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 …
  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


... Functions55/88

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 factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}

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

return;


C Style Guide56/88

UNSW Computing provides a style guide for C programs:

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


Not mandatory for COMP9024, but very useful guideline


Sidetrack: Obfuscated Code57/88

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

The International Obfuscated C Code Contest


... Sidetrack: Obfuscated Code58/88

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


... Sidetrack: Obfuscated Code59/88

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


Data Structures in C


Basic Data Types61/88


Symbolic Constants62/88

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

#define SPEED_OF_LIGHT 299792458.0

Symbolic constants used to avoid burying "magic numbers" in the code

Symbolic constants make the code easier to understand and maintain

#define NAME replacement_text

Example:
The constants TRUE and FALSE are often used when a condition with logical value is wanted. They can be defined by:

#define TRUE  1
#define FALSE 0


Basic Aggregate Data Types


Aggregate Data Types64/88

Families of aggregate data types:


Arrays65/88

An array is

Examples:

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


... Arrays66/88

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


Strings67/88

"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 Initialisation68/88

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


Exercise #5: What is the output of this program?69/88

 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  }


Array[2] = 32
String = "At"


Arrays and Functions71/88

When an array is passed as a parameter to a function

Example:

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

Within the function …


... Arrays and Functions72/88

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


Exercise #6: Arrays and Functions73/88

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

Use the prototype

int sum(int[], int)


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

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


Multi-dimensional Arrays75/88

Examples:

[Diagram:Pic/matrices-small.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 }
};


... Multi-dimensional Arrays76/88

Storage representation of multi-dimensional arrays:


[Diagram:Pic/matrices2-small.png]


... Multi-dimensional Arrays77/88

Iteration can be done row-by-row or column-by-column:

int m[NROWS][NCOLS];
int row, col;

//row-by-row
for (row = 0; row < NROWS; row++) {
    for (col = 0; col < NCOLS; col++) {
        … m[row][col] …
    }
}
// colum-by-column
for (col = 0; col < NCOLS; col++) {
    for (row = 0; row < NROWS; row++) {
        … m[row][col] …
    }
}

Row-by-row is the most common style of iteration.


Defining New Data Types78/88

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

typedef ExistingDataType NewTypeName;

Examples:

typedef float Temperature;

typedef int Matrix[20][20];

We will frequently use Bool whenever we want to stress the fact that we are interested in the logical rather than the numeric value of an expression:

typedef int Bool;


... Defining New Data Types79/88

Reasons to use typedef:


Structures80/88

A structure

Example:

struct date {
       int day;
       int month;
       int year;
}; // don't forget the semicolon!


... Structures81/88

Defining a structure itself does not allocate any memory

We need to declare a variable in order to allocate memory

struct date christmas;

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

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


... Structures82/88

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

void print_date(struct date d) {

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

int is_leap_year(struct date d) {

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


... Structures83/88

One structure can be nested inside another:

struct date { int day, month, year; };

struct time { int hour, minute; };

struct speeding {
	char        plate[7];
	double      speed;
	struct date d;
	struct time t;
};


... Structures84/88

Possible memory layout produced for TicketT object:

---------------------------------
| D | S | A | 4 | 2 | X | \0|   |        7 bytes + 1 padding
---------------------------------
|                          68.4 |                    8 bytes
-------------------------------------------------
|            27 |             7 |           2017|   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.


typedef and struct85/88

We can also define a structured data type TicketT for speeding ticket objects:

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;


... typedef and struct86/88

Note: structures can be defined in two different styles:

struct date { int day, month, year; };
// which would be used as
struct date somedate;

// or

typedef struct { int day, month, year; } DateT;
// which would be used as
DateT anotherdate;

The definitions produce objects with identical structures.

It is possible to combine both using the same identifier

typedef struct DateT { int day, month, year; } DateT;
// which could be used as
DateT        date1;
struct DateT date2;


... typedef and struct87/88

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


Summary88/88



Produced: 22 Nov 2018