0% found this document useful (0 votes)
52 views16 pages

Week 1

This document provides an introduction and overview of a university course on elementary data structures and control structures in C. It outlines the course goals, which are for students to learn fundamental data structures, algorithms, and how to analyze program efficiency. It introduces the course convenor and tutors, and notes pre-requisites are none but the course will move quickly. All course materials are available online through the listed website and learning platform.

Uploaded by

MP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views16 pages

Week 1

This document provides an introduction and overview of a university course on elementary data structures and control structures in C. It outlines the course goals, which are for students to learn fundamental data structures, algorithms, and how to analyze program efficiency. It introduces the course convenor and tutors, and notes pre-requisites are none but the course will move quickly. All course materials are available online through the listed website and learning platform.

Uploaded by

MP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data

02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

gets you thinking like a programmer


Week 1: Introduction - Elementary Data and solving problems by developing programs
expressing your ideas in the language Python
Control Structures in C
COMP9024 …

1/104 gets you thinking like a computer scientist


COMP9024 22T1 knowing fundamental data structures/algorithms
able to reason about their applicability/effectiveness
Data Structures and Algorithms 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
Aaron Quigley
step-by-step process for solving a problem  (within finite amount of space and time)

Web Site:  
www.cse.unsw.edu.au/~cs9024
... Course Goals 5/104

2/104 COMP9021 …
Course Convenor
Name: Aaron Quigley

Office: K17  HOS Office


Phone: please use Ed

Email: [email protected]
Consults: technical (course contents): Forum
technical/personal: Thursday 2-3pm (in my office)     personal: [email protected]
... Course Goals 6/104
Research: Human Computer Interaction www.hcibodi.org
Pastimes: Running, Cycling, Travel, Reading COMP9024 …

... Course Convenor 3/104

Tutors: Daria Schumm, [email protected]


Rhama Mukta, [email protected]

Kevin Luong, [email protected]


Course admin: Mei Cheng Whale [email protected]

7/104
Pre-conditions
4/104
Course Goals There are no prerequisites for this course.

However we will move at fast pace through the necessary programming fundamentals. You may find it
COMP9021 …
helpful if you are able to:

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 1/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 2/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

produce correct programs from a specification 6 Mid-term test (Wednesday) Large Assignment
understand the state-based model of computation 7 Search tree data structures quiz |
(variables, assignment, function parameters)
use fundamental data structures 8 Search tree algorithms program |
(characters, numbers, strings, arrays) 9 String algorithms, Approximation quiz |
use fundamental control structures   (if, while, for)
10 Randomised algorithms, Review program | due
know fundamental programming techniques   (recursion)
fix simple bugs in incorrect programs
11/104
Resources
8/104
Post-conditions
Textbook is a "double-header"
At the end of this course you should be able to:
Algorithms in C, Parts 1-4, Robert Sedgewick
choose/develop effective data structures (DS) Algorithms in C, Part 5, Robert Sedgewick
(graphs, search trees, …)
choose/develop algorithms (A) on these DS
(graph algorithms, tree algorithms, string algorithms, …)
analyse performance characteristics of algorithms
package a set of DS+A as an abstract data type
develop and maintain C programs

9/104
Access to Course Material
All course information is placed on the main course website:

www.cse.unsw.edu.au/~cs9024

Need to login to access material, submit homework and assignment, post on the forum, view your marks Good books, useful beyond COMP9024 (but coding style …)

Access livestream lectures, lecture recordings and quizzes (weeks 2, 4, 7, 9) on Moodle:


... Resources 12/104
COMP9024 Data Structures & Algorithms (T3-2021)
Supplementary textbook:
Always give credit when you use someone else's work. Alistair Moffat
Programming, Problem Solving, and Abstraction with C
Ideas for the COMP9024 material are drawn from Pearson Educational, Australia, Revised edition 2013, ISBN 978-1-48-601097-4

slides by Michael Thilsher (COMP9014 21T3), 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

10/104
Schedule
Week Lectures Assessment Notes
1 Introduction, C language —
2 Analysis of algorithms quiz
3 Dynamic data structures program
Also, numerous online C resources are available.
4 Graph data structures quiz
13/104
5 Graph algorithms program Lectures
https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 3/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 4/31
19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

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

present theory 1 day late: mark is capped at 10 (83.33% of the maximum possible mark)
demonstrate problem-solving methods 2 days late: mark is capped at 8 (66.67% of the maximum possible mark)
give practical demonstrations 3 days late: mark is capped at 6 (50% of the maximum possible mark)

Lectures provide an alternative view to textbook

Lecture slides will be made available before lecture ... Large Assignment 17/104

Feel free to ask questions, but No Idle Chatting


Advice on doing assignments:

14/104
They always take longer than you expect.
Problem Sets
Don't leave them to the last minute.
The weekly homework aims to:
Organising your time → no late penalty.
clarify any problems with lecture material
work through exercises related to lecture topics If you do leave them to the last minute:
give practice with algorithm design skills   (think before coding)
take the late penalty rather than copying
Problem sets available on web at the time of the lecture
18/104
Sample solutions will be posted in the following week Plagiarism
Do them yourself!   and   Don't fall behind!

15/104
Weekly Assessments
In weeks (1), 3, 5, 8, 10 :

you will be asked to submit 1 or 2 (small) programs


which will be auto-marked against one or more test cases

In weeks 2, 4, 7, 9 :
Just Don't Do it
you will be given a short quiz (4-5 questions)
with questions related to the exercises and the lecture We get very annoyed by people who plagiarise.

Programs and quizzes contribute 8% + 8% to overall mark.


... Plagiarism 19/104
Strict deadlines    (no late submissions possible, sample solutions posted right after deadline)

First assessment (week 1) is programming practice and will not count


Examples of
Plagiarism
(student.unsw.edu.au/plagiarism):
Deadline: Monday, 21 February, 5:00:00pm
1. Copying

Using same or similar idea without acknowledging the source


16/104
Large Assignment This includes copying ideas from a website, internet

The large assignment gives you experience applying tools/techniques 2. Collusion


(but to a larger programming problem than the homework)
Presenting work as independent when produced in collusion with others
The assignment will be carried out individually. This includes students providing their work to another student

The assignment will be released after the mid-term test and is due in week 10. which includes using any form of publicly readable code repository

The assignment contributes 12% to overall mark.


https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 5/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 6/31
19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

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

course) total = exam * (100/60)

For COMP9024 you will need to complete a short new online course on Academic Integrity in Programming To pass the course, you must achieve:
Courses
at least 25/60 for exam
We will ask for your completion certificate at least 50/100 for total

20/104
Mid-term Test Summary 24/104

1-hour online test in week 6 (Wednesday, 23 March, at usual time of the lecture no new content in week 6!). The goal is for you to become a better Computer Scientist
Format: more confident in your own ability to choose data structures
more confident in your own ability to develop algorithms
some multiple-choice questions able to analyse and justify your choices
some descriptive/analytical questions with short answers producing a better end-product
ultimately, enjoying the software design and development process
The mid-term test contributes 12% to overall mark.

Final Exam 21/104 C Programming Language

2-hour strain written exam during the exam period. 26/104


Why C?
Format:
good example of an imperative language
some multiple-choice questions gives the programmer great control
some descriptive/analytical questions produces fast code
many libraries and resources
The final exam contributes 60% to overall mark. main language for writing operating systems and compilers; and commonly used for a variety of
applications in industry (and science)
Must score at least 25/60 in the final exam to pass the course.

27/104
... Final Exam 22/104 Brief History of C
How to pass the mid-term test and the Final Exam: C and UNIX operating system share a complex history …

do the Homework yourself C was originally designed for and implemented on UNIX
do the Homework every week Dennis Ritchie was the author of C (around 1971)
use Weeks 1 and 2 to start practise programming in C In 1973, UNIX was rewritten in C
practise programming outside classes B (author: Ken Thompson, 1970) was the predecessor to C, but there was no A
read the lecture notes American National Standards Institute (ANSI) C standard published in 1988
read the corresponding chapters in the textbooks this greatly improved source code portability
Current standard: C11  (published in 2011)

23/104
Assessment Summary 28/104
Basic Structure of a C Program
assn1 = mark for programs/quizzes (out of 8+8)

assn2 = mark for mid-term test (out of 12)


// include files
               
               
        .

assn3 = mark for large assignment (out of 12)


// global definitions
.

exam = mark for final exam (out of 60)


// function definitions
.

function_type f(arguments) {
.

if (exam >= 25)

total = assn1 + assn2 + assn3 + exam


// local variables
// main function

int main(arguments) {

// body of function

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 7/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 8/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C
// local variables
int j = i-1;

return …;
while (j >= 0 && array[j] > element) { // logical AND

}
// body of main function
array[j+1] = array[j];

j--; // abbreviated assignment j=j-1

.
return 0;
}

.
}
array[j+1] = element; // statements terminated by ;

} // code blocks enclosed in { }

Exercise #1: What does this program compute? 29/104 int main(void) { // main: program starts here

int numbers[SIZE] = { 3, 6, 5, 2, 4, 1 }; /* array declaration

#include <stdio.h>
and initialisation */

int i;

insertionSort(numbers, SIZE);

int f(int m, int n) {


for (i = 0; i < SIZE; i++)

printf("%d\n", numbers[i]); // printf defined in <stdio>

while (m != n) {

if (m > n) {
return 0; // return program status (here: no error) to environment

m = m-n;

} else {

n = n-m;
32/104
}
Compiling with gcc
}

return m;
C source code:     prog.c
}

int main(void) {
a.out     (executable program)

printf("%d\n", f(30,18));
To compile a program prog.c, you type the following:
return 0;

}
prompt$ gcc prog.c

To run the program, type:


30/104
Example: Insertion Sort in C prompt$ ./a.out

Insertion Sort algorithm:


... Compiling with gcc 33/104
insertionSort(A):

| Input array A[0..n-1] of n elements


Command line options:
|

| for all i=1..n-1 do


The default with gcc is not to give you any warnings about potential problems
| | element=A[i], j=i-1
Good practice is to be tough on yourself:
| | while j≥0 and A[j]>element do

| | A[j+1]=A[j]
prompt$ gcc -Wall prog.c

| | j=j-1

| | end while
which reports all warnings to anything it finds that is potentially wrong or non ANSI compliant
| | A[j+1]=element

| end for The -o option tells gcc to place the compiled object in the named file rather than a.out

prompt$ gcc -o prog prog.c

... Example: Insertion Sort in C 31/104

34/104
Sidetrack: Printing Variable Values with printf()
#include <stdio.h> // include standard I/O library defs and functions

#define SIZE 6 // define a symbolic constant

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

void insertionSort(int array[], int n) { // function headers must provide types


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

int i; // each variable must have a type

for (i = 1; i < n; i++) { // for-loop syntax


format-string can use the following placeholders:
int element = array[i];

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 9/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 10/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C
%d    decimal         %f    floating-point ... Assignments 38/104
%c    character         %s    string
\n    new line         \"    quotation mark C assignment statements are really expressions

Examples: they return a result: the value being assigned


the return value is generally ignored
num = 3;

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


Frequently, assignment is used in loop continuation tests
The cube of 3 is 27.
to combine the test with collecting the next value
to make the expression of such loops more concise
id = 'z';

num = 1234567;

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


Example: The pattern

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


v = getNextItem();

while (v != 0) {

Can also use width and precision: process(v);

printf("%8.3f\n", 3.14159);

v = getNextItem();

3.142

is often written as

while ((v = getNextItem()) != 0) {

Algorithms in C process(v);

36/104
Basic Elements 39/104
Exercise #2: What are the final values of a and b?
Algorithms are built using
1.
assignments a = 1; b = 5;

conditionals while (a < b) {

a++;

loops b--;

function calls/return statements }

2.
37/104 a = 1; b = 5;

Assignments while ((a += 2) < b) {

b--;

In C, each statement is terminated by a semicolon ; }

Curly brackets { } used to enclose statements in a block


Usual arithmetic operators: +, -, *, /, %
Usual assignment operators: =, +=, -=, *=, /=, %= 1. a == 3, b == 3
The operators ++ and -- can be used to increment a variable (add 1) or decrement a variable (subtract 2. a == 5, b == 4
1)
It is recommended to put the increment or decrement operator after the variable:
41/104
Conditionals
// suppose k=6 initially
k++; // increment k by 1; afterwards, k=7
n = k--; // first assign k to n, then decrement k by 1
if (expression) {

// afterwards, k=6 but n=7


some statements;

It is also possible (but NOT recommended) to put the operator before the variable:
if (expression) {

// again, suppose k=6 initially


some statements1;

++k; // increment k by 1; afterwards, k=7


n = --k; // first decrement k by 1, then assign k to n
} else {

// afterwards, k=6 and n=6


some statements2;

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 11/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 12/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

some statements executed if, and only if, the evaluation of expression is non-zero 2. What is the resulting value of x after the following assignment?
some statements1 executed when the evaluation of expression is non-zero
some statements2 executed when the evaluation of expression is zero x = (x >= 0) + (x < 0);

Statements can be single instructions or blocks enclosed in { }


1. The condition is unsatisfiable, hence the output will always be
... Conditionals 42/104
Nay

Indentation is very important in promoting the readability of the code 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


Each logical block of code is indented:

// Style 1
            // Style 2 (my preference)
            // Preferred else-if style
46/104
if (x)
if (x) {
if (expression1) {
Loops
{
statements;
statements1;

statements;
}
} else if (exp2) {
C has two different "while loop" constructs
}
statements2;

} else if (exp3) {
// while loop
                // do .. while loop

statements3;
while (expression) {
do {

} else {
some statements;
some statements;

statements4;
}
} while (expression);

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

... Conditionals 43/104


... Loops 47/104
Relational and logical operators
The "for loop" in C
a > b a greater than b for (expr1; expr2; expr3) {

a >= b a greater than or equal b some statements;

a < b a less than b


expr1 is evaluated before the loop starts
a <= b a less than or equal b expr2 is evaluated at the beginning of each loop
if it is non-zero, the loop is repeated
a == b a equal to b expr3 is evaluated at the end of each loop
a != b a not equal to b  
a && b a logical and b Example:     for (i = 1; i < 10; i++) {

printf("%d %d\n", i, i * i);

a || b a logical or b
! a logical not a
Exercise #4: What is the output of this program? 48/104

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


int i, j;

for (i = 8; i > 1; i /= 2) {

Exercise #3: Conditionals 44/104 for (j = i; j >= 1; j--) {

printf("%d%d\n", i, j);

}
1. What is the output of the following program fragment?
printf("\n");

if ((x > y) && !(y-x <= 0)) {


}

printf("Aye\n");

} else {

88

printf("Nay\n");

87

..

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 13/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 14/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

81
}

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

41
return;

22

21

Data Structures in C

54/104
50/104
Basic Data Types
Functions
In C each variable must have a type
Functions have the form C has the following generic data types:

return-type function-name(parameters) {
char     character     'A', 'e', '#', …
int     integer     2, 17, -5, …
declarations
float     floating-point number     3.14159, …
statements
double     double precision floating-point     3.14159265358979, …

return …;
There are other types, which are variations on these
}

Variable declaration must specify a data type and a name; they can be initialised when they are
if return_type is void then the function does not return a value declared:
if parameters is void then the function has no arguments
float x;

char ch = 'A';

51/104
int j = i;

... Functions

When a function is called: 55/104


Aggregate Data Types
1. memory is allocated for its parameters and local variables
2. the parameter expressions in the calling function are evaluated Families of aggregate data types:
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 homogeneous … all elements have same base type
4. local variables need to be assigned before they are used   (otherwise they will have "garbage" values) arrays (e.g. char s[50], int v[100])
5. function code is executed, until the first return statement is reached heterogeneous … elements may combine different base types
structures (e.g. struct student { char name[30]; int zID; })

... Functions 52/104


56/104
Arrays
When a return statement is executed, the function terminates:
An array is
return expression;

a collection of same-type variables


1. the returned expression will be evaluated arranged as a linear sequence
2. all local variables and parameters will be thrown away when the function terminates accessed using an integer subscript
3. the calling function is free to use the returned value, or to ignore it for an array of size N, valid subscripts are 0..N-1
Example:
Examples:

// Euclid's gcd algorithm (recursive version)


int a[20]; // array of 20 integer values/variables

int euclid_gcd(int m, int n) {

if (n == 0) {

char b[10]; // array of 10 character values/variables

return m;

} else {
return euclid_gcd(n, m % n);

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 15/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 16/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

... Arrays 57/104 a working C program


whose appearance is obscure
Larger example: whose functionality unfathomable
Web site: www.ioccc.org
#define MAX 20
100's of examples of bizarre C code
(understand these → you are a C master)
int i; // integer value used as index

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

... Sidetrack: C Style 61/104


fact[0] = 1;

for (i = 1; i < MAX; i++) {


Most artistic code (Eric Marshall, 1986)
fact[i] = i * fact[i-1];

extern int

errno

;char

58/104
Sidetrack: C Style ;main(
grrr

r,

argv, argc ) int argc ,

We can define a symbolic constant at the top of the file r ; char *argv[];{int P( );

#define x int i, j,cc[4];printf(" choo choo\n" ) ;

#define SPEED_OF_LIGHT 299792458.0


x ;if (P( ! i ) | cc[ ! j ]

#define ERROR_MESSAGE "Out of memory.\n"


& P(j )>2 ? j : i ){* argv[i++ +!-i]

; for (i= 0;; i++ );

_exit(argv[argc- 2 / cc[1*argc]|-1<4 ] ) ;printf("%d",P(""));}}

Symbolic constants make the code easier to understand and maintain P ( a ) char a ; { a ; while( a > " B "

/* - by E ricM arsh all- */); }

#define NAME replacement_text

The compiler's pre-processor will replace all occurrences of NAME with replacement_text 62/104
it will not make the replacement if NAME is inside quotes ("…") or part of another name ... Sidetrack: C Style

Just plain obscure (Ed Lycklama, 1985)


... Sidetrack: C Style 59/104
#define o define

UNSW Computing provides a style guide for C programs: #o ___o write

#o ooo (unsigned)

#o o_o_ 1

C Coding Style Guide


   (http://wiki.cse.unsw.edu.au/info/CoreCourses/StyleGuide)
#o _o_ char

#o _oo goto

#o _oo_ read

Not strictly mandatory for COMP9024, but very useful guideline #o o_o for

#o o_ main

Style considerations that do matter for your COMP9024 assignments: #o o__ if

#o oo_ 0

#o _o(_,__,___)(void)___o(_,__,ooo(___))

use proper layout, including consistent indentation


#o __o (o_o_<<((o_o_<<(o_o_<<o_o_))+(o_o_<<o_o_)))+(o_o_<<(o_o_<<(o_o_<<o_o_)))

3 spaces throughout, or 4 spaces throughout o_(){_o_ _=oo_,__,___,____[__o];_oo ______;_____:___=__o-o_o_; _______:

do not use TABs _o(o_o_,____,__=(_-o_o_<___?_-o_o_:___));o_o(;__;_o(o_o_,"\b",o_o_),__--);

keep functions short and break into sub-functions as required _o(o_o_," ",o_o_);o__(--___)_oo _______;_o(o_o_,"\n",o_o_);______:o__(_=_oo_(

use meaningful names (for variables, functions etc) oo_,____,__o))_oo _____;}

use symbolic constants to avoid burying "magic numbers" in the code


comment your code
63/104
Strings
... Sidetrack: C Style 60/104
"String" is a special word for an array of characters

C has a reputation for allowing obscure code, leading to … end-of-string is denoted by '\0' (of type char and always implemented as 0)

The International Obfuscated C Code Contest Example:

Run each year since 1984 If a character array s[11] contains the string "hello", this is how it would look in memory:
Goal is to produce
https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 17/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 18/31
19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

0 1 2 3 4 5 6 7 8 9 10
int value = atoi(string);

---------------------------------------------

| h | e | l | l | o | \0| | | | | |
Example:
---------------------------------------------

#include <stdio.h> // includes definition of and scanf()

#include <stdlib.h> // includes definition of atoi()

64/104
Array Initialisation #define INPUT_STRLEN 20

...
Arrays can be initialised by code, or you can specify an initial set of values in declaration.
char str[INPUT_STRLEN];

int n;
Examples:
printf("Enter a string: ");
char s[6] = {'h', 'e', 'l', 'l', 'o', '\0'};
scanf("%19s", str);

n = atoi(str);

printf("You entered: \"%s\". This converts to integer %d.\n", str, n);

char t[6] = "hello";

Enter a string: 9024

int fib[20] = {1, 1};


You entered: "9024". This converts to integer 9024.

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

68/104
In the third case, fib[0] == fib[1] == 1 while the initial values fib[2] .. fib[19] are Arrays and Functions
undefined.
When an array is passed as a parameter to a function
In the last case, C infers the array length   (as if we declared vec[5]).
the address of the start of the array is actually passed

Exercise #5: What is the output of this program? 65/104 Example:

int total, vec[20];

1 #include <stdio.h>

2
total = sum(vec);

3 int main(void) {

4 int arr[3] = {10,10,10};


Within the function …
5 char str[] = "Art";

6 int i;
the types of elements in the array are known
7
the size of the array is unknown
8 for (i = 1; i < 3; i++) {

9 arr[i] = arr[i-1] + arr[i] + 1;

10 str[i] = str[i+1];
... Arrays and Functions 69/104
11 }

12 printf("Array[2] = %d\n", arr[2]);


Since functions do not know how large an array is:
13 printf("String = \"%s\"\n", str);

14 return 0;
pass in the size of the array as an extra parameter, or
15 } include a "termination value" to mark the end of the array

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


Array[2] = 32

String = "At"
int total, vec[20];

total = sum(vec,20);

67/104
Sidetrack: Reading Variable Values with scanf() and atoi() 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).
Formatted input read from standard input (e.g. keyboard)

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


Exercise #6: Arrays and Functions 70/104

Converting string into integer Implement a function that sums up all elements in an array.

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 19/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 20/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

Use the prototype typedef float Real;

Real complex_calculation(Real a, Real b) {

int sum(int[], int)


Real c = log(a+b); … return c;

int sum(int vec[], int dim) {


"package up" complex type definitions for easy re-use
int i, total = 0;
many examples to follow; Matrix is a simple example

for (i = 0; i < dim; i++) {

total += vec[i];
75/104
}

Structures
return total;

}
A structure

is a collection of variables, perhaps of different types, grouped together under a single name
72/104 helps to organise complicated data into manageable entities
Multi-dimensional Arrays exposes the connection between data within an entity
is defined using the struct keyword
Examples:
Example:

typedef struct {

char name[30];

int zID;

} StudentT;

... Structures 76/104

Note:   q[0][1]==2.7    r[1][3]==8    q[1]=={3.1,0.1} One structure can be nested inside another:
Multi-dimensional arrays can also be initialised: typedef struct {

int day, month;

float q[][] = {
} DateT;

{ 0.5, 2.7 },

{ 3.1, 0.1 }
typedef struct {

};
int hour, minute;

} TimeT;

73/104
Sidetrack: Defining New Data Types typedef struct {

char plate[7]; // e.g. "DSA42X"

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

DateT d;

typedef ExistingDataType NewTypeName;


TimeT t;

} TicketT;

Examples:

typedef float Temperature;


... Structures 77/104

typedef int Matrix[20][20];


Possible memory layout produced for TicketT object:

---------------------------------

... Sidetrack: Defining New Data Types 74/104


| D | S | A | 4 | 2 | X | \0| | 7 bytes + 1 padding

---------------------------------

Reasons to use typedef: | 68.4 | 8 bytes

---------------------------------

give meaningful names to value types   (documentation) | 2 | 6 | 8 bytes

is a given number Temperature, Dollars, Volts, …? ---------------------------------

allow for easy changes to underlying type


https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 21/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 22/31
19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

| 20 | 45 | 8 bytes
return ( (d.month >= 6) && (d.month <= 8) );

---------------------------------
}

 
Note: padding is needed to ensure that plate lies on an 8-byte block. Data Abstraction
Don't normally care about internal layout, since fields are accessed by name.
82/104
Abstract Data Types
... Structures 78/104
A data type is …
Defining a structured data type itself does not allocate any memory
a set of values   (atomic or structured values)     e.g. integer stacks
We need to declare a variable in order to allocate memory a collection of operations on those values   e.g. push, pop, isEmpty?

DateT christmas;
An abstract data type …

The components of the structure can be accessed using the "dot" operator is a logical description of how we view the data and operations
without regard to how they will be implemented
christmas.day = 25;
creates an encapsulation around the data
christmas.month = 12;
is a form of information hiding

... Structures 79/104

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


83/104
for (i = 0; i < NUM_TICKETS; i++) {

... Abstract Data Types


printf("%s %6.2f %d/%d at %d:%d\n", tickets[i].plate,

tickets[i].speed,
Users of the ADT see only the interface
tickets[i].d.day,

tickets[i].d.month,
Builders of the ADT provide an implementation
tickets[i].t.hour,

tickets[i].t.minute);

ADT interface provides

// Sample output:
a user-view of the data structure
//
function signatures (prototypes) for all operations
// DSA42X 68.40 2/6 at 20:45
semantics of operations (via documentation)
⇒  a "contract" between ADT and its clients

... Structures 80/104 ADT implementation gives

A structure can be passed as a parameter to a function: concrete definition of the data structures
function implementations for all operations
void print_date(DateT d) {

printf("%d/%d\n", d.day, d.month);


... Abstract Data Types 84/104
}

ADT interfaces are opaque


int is_winter(DateT d) {

clients cannot see the implementation via the interface

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 23/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 24/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

ADTs are important because … Stack vs Queue 88/104

facilitate decomposition of complex programs


make implementation changes invisible to clients Queue, aka FIFO data structure (first in, first out)
improve readability and structuring of software
allow for reuse of modules in other systems Insert and delete are called enqueue and dequeue

Applications:
85/104
ADOs and ADTs the checkout at a supermarket
people queueing to go onto a bus
We want to distinguish … objects flowing through a pipe (where they cannot overtake each other)
chat messages
ADO = abstract data object web page requests arriving at a web server
ADT = abstract data type printing jobs arriving at a printer

Warning: Sedgewick's first few examples are ADOs, not ADTs.

Exercise #7: Stack vs Queue 89/104


86/104
Example: Abstract Stack Data Object
Consider the previous example but with a queue instead of a stack.
Stack, aka pushdown stack or LIFO data structure (last in, first out)
Which element would have been taken out ("dequeued") first?
Assume (for the time being) stacks of char values

Operations:
a
create an empty stack
insert (push) an item onto stack
remove (pop) most recently pushed item 91/104
check whether stack is empty
Stack as ADO
Applications: Interface (a file named Stack.h)

undo sequence in a text editor // Stack ADO header file

bracket matching algorithm


… #define MAXITEMS 10

void StackInit(); // set up empty stack

87/104 int StackIsEmpty(); // check whether stack is empty

... Example: Abstract Stack Data Object void StackPush(char); // insert char on top of stack

char StackPop(); // remove char from top of stack

Example of use:
Note:
Stack    Operation    Return value
no explicit reference to Stack object
?    create    - this makes it an Abstract Data Object (ADO)
-    isempty    true
-    push a    - ... Stack as ADO 92/104

a    push b    - Implementation may use the following data structure:


ab    push c    -
abc    pop    c
ab    isempty    false

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 25/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 26/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

6. not balanced (case 3: missing closing bracket)

... Stack as ADO 96/104

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

... Stack as ADO 93/104 |

| for each ch in s do

| | if ch = open bracket then

Implementation (in a file named Stack.c): | | push ch onto stack

| | else if ch = closing bracket then

| | | if stack is empty then

#include "Stack.h"
| | | return false // opening bracket missing (case 1)

#include <assert.h>
| | | else

| | | pop top of stack

// define the Data Structure

typedef struct {
// insert char on top of stack

| | | if brackets do not match then

char item[MAXITEMS];
void StackPush(char ch) {
| | | return false // wrong closing bracket (case 2)

int top;
assert(stackObject.top < MAXITEMS-1);
| | | end if

} stackRep;
stackObject.top++;
| | | end if

int i = stackObject.top;
| | end if

// define the Data Object


stackObject.item[i] = ch;
| end for

static stackRep stackObject;


}

| if stack is not empty then return false // some brackets unmatched (case 3)

// set up empty stack


// remove char from top of stack
| else return true

void StackInit() {
char StackPop() {

stackObject.top = -1;
assert(stackObject.top > -1);

}
int i = stackObject.top;

char ch = stackObject.item[i];
... Stack as ADO 97/104
// check whether stack is empty
stackObject.top--;

int StackIsEmpty() {
return ch;

return (stackObject.top < 0);


}
Execution trace of client on sample input:
}

( [ { } ] )

assert(test) terminates program with error message if test fails


static Type Var declares Var as local to Stack.c
Next char    Stack    Check
-   empty   -

Exercise #8: Bracket Matching 94/104 (   (   -


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

Which of the following expressions are balanced? }   ([   {  vs  }   ✓

1. (a+b) * c ]   (   [  vs  ]   ✓
2. a[i]+b[j]*c[k]) )   empty   (  vs  )   ✓
3. (a[i]+b[j])*c[k]
4. a(a+b]*c eof   empty   -
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 98/104
Exercise #9: Bracket Matching Algorithm

1. balanced Trace the algorithm on the input


2. not balanced (case 1: an opening bracket is missing)
3. balanced void f(char a[], int n) {

4. not balanced (case 2: closing bracket doesn't match opening bracket) int i;

5. balanced for(i=0;i<n;i++) { a[i] = a[i]*a[i])*(i+1); }

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 27/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 28/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C 19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

convert program source code to executable form


Next bracket    Stack    Check "executable" might be machine code or bytecode

start   empty   - The Gnu C compiler (gcc)

(   (   - applies source-to-source transformation (pre-processor)


compiles source code to produce object files
[   ([   - links object files and libraries to produce executables
]   (   ✓
)   empty   ✓
{   {   -
(   {(   -
)   {   ✓
{   {{   -
[   {{[   -
]   {{   ✓ ... Compilers 103/104

[   {{[   - 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

)   {   false
gcc -o rbt brackets.o Stack.o

links brackets.o, Stack.o and libraries

Exercise #10: Implement Bracket Matching Algorithm in C 100/104 producing executable program called rbt

Note that stdio,assert included implicitly.


Use Stack ADT
gcc is a multi-purpose tool
#include "Stack.h"

compiles (-c), links, makes executables (-o)


Sidetrack: Character I/O Functions in C   (requires <stdio.h>)

int getchar(void);
104/104
Summary
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) Introduction to Algorithms and Data Structures
C programming language, compiling with gcc
int putchar(int ch);
Basic data types (char, int, float)
Basic programming constructs (if … else conditionals, while loops, for loops)
writes the character ch to standard output Basic data structures (atomic data types, arrays, structures)
returns the character written, or EOF on error Introduction to ADTs
Compilation

Managing Abstract Data Types and Objects in C


Suggested reading (Moffat):
introduction to C … Ch. 1; Ch. 2.1-2.3, 2.5-2.6;
102/104
Compilers conditionals and loops … Ch. 3.1-3.3; Ch. 4.1-4.4
arrays … Ch. 7.1, 7.5-7.6
Compilers are programs that structures … Ch. 8.1

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 29/31 https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 30/31


19/02/2022, 17:24 Week 1: Introduction - Elementary Data and Control Structures in C

Suggested reading (Sedgewick):


introduction to ADTs … Ch. 4.1-4.3

Coming up …
Principles of algorithm analysis ([S] 2.1-2.4, 2.6)

Produced: 13 Feb 2022

https://www.cse.unsw.edu.au/~cs9024/22T1/lecs/week1/notes.html 31/31

You might also like