combined textbook - comp1917 2011s1 - textbook - 2011s1 - …openlearning/2011s1/textbook.pdf ·...

77
Open Learning » Comp1917 » 2011s1 » TextBook » Combined TextBook - Comp1917 2011s1 Combined TextBook - Comp1917 2011s1 Computing 1 Textbook 2011s1 UNSW Jointly written by the students of the course Contents 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 Revision Contents studyNotes - binary - scanf - bmp formatting - writing arrays to sockets - pointers - Malloc - Strings - Abstract Data Types (ADT's) - typedefs & structs - getchar & putchar Chapter 00 - a beautiful picture of toast Chapter 01 - Toast - not giving up Chapter 02 Syntax - #define Ideas - 4001 - Abstraction, emergence Other - Turing computers - Toast, Bagels Nomic Chapter 03 Syntax Ideas - Byte - 4003 processor - 4004 processor - plagiarism Other - link to the lecture videos Chapter 04 Syntax - gcc commands Ideas - subtle rules Other - link to putty instructions Chapter 05 Syntax - the 'template' for c files - #include - #EXIT_SUCCESS Ideas - many people working on one thing Other Chapter 06 Syntax » Edit Page Attributes Attachments History Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex... 1 of 77 20/06/11 10:10 AM

Upload: others

Post on 18-Aug-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Open Learning » Comp1917 » 2011s1 » TextBook » Combined TextBook - Comp1917 2011s1

Combined TextBook - Comp1917 2011s1Computing 1 Textbook2011s1 UNSWJointly written by the students of the course

Contents0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47Revision

ContentsstudyNotes- binary- scanf- bmp formatting- writing arrays to sockets- pointers- Malloc- Strings- Abstract Data Types (ADT's)- typedefs & structs- getchar & putchar

Chapter 00- a beautiful picture of toast

Chapter 01- Toast- not giving up

Chapter 02Syntax- #defineIdeas- 4001- Abstraction, emergenceOther- Turing computers- Toast, Bagels Nomic

Chapter 03SyntaxIdeas- Byte- 4003 processor- 4004 processor- plagiarismOther- link to the lecture videos

Chapter 04Syntax- gcc commandsIdeas- subtle rulesOther- link to putty instructions

Chapter 05Syntax- the 'template' for c files- #include- #EXIT_SUCCESSIdeas- many people working on one thingOther

Chapter 06Syntax

» Edit Page Attributes Attachments History

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

1 of 77 20/06/11 10:10 AM

Page 2: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

- 'If' statements (and else statements)- integers (ints)- scanfIdeas- Testing- True and False- nesting (indentation)- returning from inside an if statement (NOT TO BE DONE UNDER ANY CIRCUMSTANCES)Other- First mention of Next Thursday- leapyears

Chapter 07Syntax- assertsIdeas- binary- relevant variable names- responsibility for input- magic numbers & #defines- style guide- functionsOther- leap years- turing complete machines

Chapter 08SyntaxIdeas- size of different data types- hexadecimal (base 16)- ASCII chart- Data types- Floats- signed ints (integers)Other- Forum rules

Chapter 09- Procrastinating- commenting in code- size of ints changing- void functions- implicit declaration errors- using doubles- statement with no effect error- functions- ASCII table

Chapter 10- side effects- clarity- Portfolio attributes- Group work problem solution- bmp file- overflow- testing tips- sizeof (find the size of a variable)- pointer (address of a variable)- logical operators (&& and ||)

Chapter 11- blank

Chapter 12- repetition- referencing- loops (while loops)

Chapter 13- duplpication and repetition- common while loop faults- fence post errors- how functions work

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

2 of 77 20/06/11 10:10 AM

Page 3: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

- properties of functions

Chapter 14- wondrous numbers- recursion- nested loops- flags

Chapter 15- 8004 processor

Chapter 16- more on forum rules- assignment management- planning & the spec- writing new notes on the wiki- style & good code- testing code (different types of testing)- how often to practice coding

Chapter 17- machine code- flow control- data abstraction- separating user data from control data- a little on strings- pointers and why we use them- variables vs pointers, pros and cons- c syntax (&, *, %s, %p)

Chapter 18- more on strings- strlen() and string.h- distinction between program and data- strings vs characters- arrays - buffer overflow (and how you'll lose 5 marks for each one in the exam)

Chapter 19 (Extension Lecture)- rules in systems and the resulting complexity- the square, circle, triangle game.- multiplication- chickens, eggs, and complex numbers- first mention of Mandelbrot- fractals- web servers- telnet- task 2

Chapter 20- student reps- mandelbrot zooming- outputting BMP- writing pixels to a server

Chapter 21- library functions are free to be usedChapter 22- stepsToRed function- Richard's server has a bug- spec change- adaptability of programs- structs and typedef- Standardisation and American spelling. (so I should put a z in there)- the opening of Pandora's box, the syntax has been freed!Chapter 23- Risk management - Hacking - ColoursChapter 24- blank, page does not existChapter 25- Portfolio attributes- stacks, memory and stackframes- a little on Malloc

Chapter 26- More on Malloc

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

3 of 77 20/06/11 10:10 AM

Page 4: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

- the Free function- more on Portfolio (including links)- interesting uses for toastersChapter 27- first mention of Major Project- Abstract Data types (ADT's)- importance of the spec (USBs)

Chapter 28-trading students in the University simulation

Chapter 29- revision of data types- pointers, and how C reads them- creating new types- designing a stack

Chapter 30- the Laptop games rule- Stacks- KISS (the acronym) for interfaces- rules for being awesome- testing abstract types

Chapter 31- Does not exist

Chapter 32- Abstract Data types (ADT's)

Chapter 33- cuttlefishes- looking at averages- a little on portfolios- finding Henry- The fish in the Mandelbrot server (unrelated: lets think of some names for the fish)- debugging code- the psychology of debugging- ships and logs- software projects

Chapter 35- Queue.c

Chapter 36- Why arrays are good/bad- Linked lists

COMP1917 Lecture 0, Week 0

Chapter 00

Toast is mostly really really good

_ __ _ __

( `^` )) ( `^` ))

| || | ||

| || | ||

'-----'` '-----'`

Next Chapter

COMP1917 Lecture 1, Week 1

Chapter 01

Stirring Deeds of Britain's Sea DogsIn computing, like most other skills, talking about it is interesting but you're not going to learn anything until you do it "Its gotta be in yourfingertips not just in your ears"

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

4 of 77 20/06/11 10:10 AM

Page 5: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

"Programming is a never ending series of puzzles and challenges." Computing can solve problems, it can make things and it can help people.

Toast problem"How many pieces of toast would it take to fill a lecture theatre?" How many cubic metres are in the theatre? How tall is the lecturer? The point ofthe toast exercise is there is no universal consensus on how to solve problems.

If you can't solve a problem:

1. It is important not to give up as the solution might be right in front of you or a page turn away.2. Ask lots of questions3. Break it up into parts(unitisation)

When you finally get the answer, try to solve it another way rather than leaving it.

AbstractionThe art of seeing things at different levels. The lecturer is a human being, he is a billion cells, he is a lot of organic molecules. Different levels ofabstraction - different levels of looking at the same thing.

Different kinds of problem require different level of abstraction - enhancing, going down, and abstracting, going up. If you do everything at theatom level, everything gets complicated quickly. But if you do everything at the top level everything gets wishy washy and you can't do anything.

Previous Chapter | Next Chapter

COMP1917 Lecture 2, Week 1

Chapter 02DefinitionsAbstraction

Reducing the information content of a concept to retain only information which is relevant.

Emergence

The way complex systems and patterns arise out of a multiplicity of relatively simple interactions.

MicroprocessorsOrder of Operations

Number is loaded onto IP first.1.Contents of the address number indicated on IP is loaded2.IP is increased by One or Two(depending on the instruction size - one byte or two bytes)3.Instruction is executed4.

Rationale for such order: This is so that two byte instruction requiring jumping action can be executed properly.(Having IP increase at last stage willoverride the settings)

Registers

IP instruction pointer (what instruction number we are up to)IS instruction store (stores the instruction that we are up to)R general register

4000 series microprocessorsHow to tell if something is a computer or a sentient being.(Not quite like telling whether something is a function ora computer). Oliver Tan (Wed18NSBHS)

Michael reckons that neither a player piano, a 4000,4001 or 4002 are computers.

4000

One byte instructions'' HaltX Beep

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

5 of 77 20/06/11 10:10 AM

Page 6: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

0 Pause

4001

16 bit memoryRegisters: IP, IS, R

One byte instructions0 Halt1 R = R+12 R = R+23 R = R+44 R = R+87 Print R

4002

16 bit memoryRegisters: IP, IS, R

One byte instructions0 Halt1 R = R+12 R = R-17 Print R

OTHER BAKING RELATED STUFFS

How much Toast can fit in a lecture HallWe learnt How to cook toast "YUM",did you know bread stays the same size if you toast it?Solution One: Start Toasting bread, (Great Approach if you are stuck)How to make a bagelget Ingredients (inputs)give Ingredients to a baker(function)get bagel of the baker (output)how to play Nomicstart with a game with no ruleseach player takes turns creating a ruleplayers should try not to create rules that let them directly win

Previous Chapter | Next Chapter

COMP1917 Lecture 3, Week 1

Chapter 03DEFINITIONS

BYTE: the smallest unit of memory referable by name. 1 byte = 8 bits.

4003 PROCESSOR16 memory cellsSystem Registers: IP, ISGeneral registers: R0, R1

One byte instructions Two byte instructions0 Halt 8 Jump to <address> if R0 != 01 Increment R0 (R0 = R0+1) 9 Jump to <address> if R0 == 02 Decrement R0 (R0 = R0-1)3 Increment R1 (R1 = R1+1)4 Decrement R1 (R1 = R1-1)5 Swap R0 and R1 (Swap R0 <-> R1)6 Beep7 Print R0

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

6 of 77 20/06/11 10:10 AM

Page 7: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

4004 processorRegisters: IP, ISTwo general registers: R0, R1

One byte instructions Two byte instructions0 - Halt 8 - Jump to <address> if R0 != 01 - R0 = R0+1 9 - Jump to <address> if R0 == 02 - R0 = R0-1 10 - <value> -> R03 - R1 = R1+1 11 - <value> -> R14 - R1 = R1-1 12 - R0 -> <address>5 - R0=R0+R1 13 - R1 -> <address>6 - R0=R0-R1 14 - R0 <-> <address>7 - Print R0 15 - R1 <-> <address>

ADDITION PROGRAM on 4003Conceptualize two piles. To help think of a solution.Adding is moving the pieces from one pile to another, until one pile is empty. The only 'pile' that we can test for emptiness is R0, so that is the 'pile'to take pieces from.After moving the pieces, we can swap the memory stores, and print R0, which is now the pile containing the addition of the two values. Here is theexample code to add '1' and '1':(note that one and one are 'loaded' in by the first two digits of the program.)

1 3 9 12

2 3 8 2

0 0 0 0

5 7 6 0

General knowledgePlagiarism is bad, mkay. Worse than eating in the lecture theatre, which is okay if you're clean.Listening to criticism is great. Be constructive when criticising others' work. Administrative detailsWe should always be trying to find potential obstructions to our learning and removing them, e.g. if we have the whole day of computing lecturesand find it difficult to concentrate.Written based on lecture three, videos located hereCourse textbook is ''Programming, Problem Solving, and Abstraction with C'' by Alistair Moffat.Course OutlineCourse Style Guide

Previous Chapter | Next Chapter

COMP1917 Lecture 4, Week 1

CHAPTER 04DEFINITIONS

TEXT_EDITOR: Program that edits text files in variety of formats.COMPILE: Process of turning 'programming code'(Eg. C, C++ etc.) into 'machine code'(4003 Microprocessor instructions etc.)

COMPILING & RUNNING PROGRAMCompiling

Compile using:

gcc -Wall -Werror -O -o hello hello.c

gcc: Compile command for compiling gcc-Wall -Werror: make all warnings errors. Halts the compiling if the error found-O: optimise our program.-o: output executable with file name "hello" useing source file "hello.c"

Running

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

7 of 77 20/06/11 10:10 AM

Page 8: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Run the program opening the executable. For linux use the command "./fileName" in console.

./hello

Example

Example of a simple C program (source code)

1 2 3 4 5 6 7 8 91011121314

#include <stdlib.h>#include <stdio.h>

int main(int argc, char * argv[]) {

int x;x = 9001;

printf("Hello world! \n");printf("My favourite number is: %d",x);if (x > 9000) {

printf("Whatever");}

}

NB. argc is a count of the arguments supplied to the program while argv is an array of pointers to the strings which are those arguments

printf codescode | type | example

c |Character | a

d or i |Signed decimal integer | 392

e |Scientific notation (mantise/exponent) using e character |3.9265e+2

E |Scientific notation (mantise/exponent) using E character |3.9265E+2

f| Decimal floating point | 392.65

g| Use the shorter of %e or %f | 392.65

G| Use the shorter of %E or %f | 392.65

o| Unsigned octal | 610

s| String of characters | sample

u| Unsigned decimal integer | 7235

x| Unsigned hexadecimal integer | 7fa

X| Unsigned hexadecimal integer (capital letters) | 7FA

p| Pointer address | B800:0000

n| Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored.

%| A % followed by another % character will write % to stdout.| %

length description:

h: The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X).

l: The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide characterstring for specifiers c and s.

L: The argument is interpreted as a long double (only applies to floating point specifiers: e, E, f, g and G).

GENERAL INFORMATION

Use Putty to connect to a university server/lab computers from home:|Putty InstructionsTo transfer files between home and the university server/lab computers use WinSCP: |WinSCP instructions

Previous Chapter | Next Chapter

COMP1917 Lecture 5, Week 2

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

8 of 77 20/06/11 10:10 AM

Page 9: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

CHAPTER 05GENERAL PROGRAMMING STRUCTUREProgram Descriptions

Required at the top of every program.

12345

/* * "fileName.c" * "Short Description of program" * "Name of Author/Authors and Date" */

Header Files

The "#include" command includes source code from other files in your program.

12345

#include <stdio.h>#include <stdlib.h>#include <assert.h>#include <string.h>#include "thatFileIWrote.h"

Main Function & Return Function

The runtime environment calls the main function to begin program execution. EXIT_SUCCESS is a define statement located in <stdlib.h> It valueis 0, return EXIT_SUCCESS from your main function.

1234567

int main (int argc, char* argv[]){ printf ("int argc, char* argv[]; allows you to input variables at console"); printf ("C really cares about UpPer and LowEr Case LeTTers"); printf ("Hello Julian...\n"); return EXIT_SUCCESS; }

GENERAL INFORMATIONRichards Programming Advice

When your program is not working you should go to the beach(take a break) or try a different approach.Don't hit it with a hammer, panic or go topieces. Try again later or just do the best you can.

Programming at UNSW

The University uses the linux Operating System. It also mainly uses MAC computers. Your Tutor can help you with any issues or problems youmay encounter. Putty is a text based terminal emulator that you can use to connect to the lab server/computer.Connect using cse.unsw.edu.au as thehostname, then log in using your CSE username and password. You can save these credentials for later use, you may also edit the backgroundcolour. Please note:whenever you see a security question in windows you say yes (or I Give UP, I SURRENDER),save save save save save, hit it 5times in windows. For Unix Commands please see "|Unix Commands"

Course Administration

Only use c functions/commands post them being covered in the course, or if Richard has said you can use them. Check with your tutor forclarification. Completion of tasks will be rewarded with a pixel.

Richards Deep and Meaningful

two problems in computing large teams of people working on software many people working on the same thing many cooks trying to cook bagelshow can we get many brains to work together as one * concurrency control (only one person working on it at a time)

Previous Chapter | Next Chapter

COMP1917 Lecture 6, Week 2

CHAPTER 06

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

9 of 77 20/06/11 10:10 AM

Page 10: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

DEFINITIONSTRUE and FALSE

TRUE and FALSE should be defined as we haven't worked with stdbool.h.Note that usually TRUE and FALSE is translated into 1 & 0

12#define TRUE 1 #define FALSE 0

return

return "value" returns a value/variable from the function. It is usually situated at the end of the function.

BODMAS order

(as in powers of), division, multiplication, addition, subtraction C uses BODMAS to evaluate expressions

IF STATEMENTChecks if the if("input"){} is not FALSE i.e '0'.If it is TRUE i.e input!=0 it will include the code within "{someCode()}" into your program. otherwise it will include the code after theelse"{someCode()}". If there is no else statement and input!=0 the "if statement" will do nothing.

12345

if (magicNumber <= 9001) { printf("I really love you man!");} else { printf("You guessed wrong!\n");}

Alternatively, 'else' can be further specified using 'else if'

1234567

if (magicNumber <= 9001) { printf("I really love you man!");} else if (magicNumber > 9001 && magicNumber <= 9005) { printf("You are close!\n");} else { printf("You guessed wrong!\n");}

Nesting of IFs

123456

if (magicNumber > 9000) { printf("I like Danes!"); if (magicNumber <= 9001) { printf("I really love you man!"); }}

Scanning of User InputReads in a variable with type defined by "%.."(Eg. %d, %f, %l, %l...) and stores it in the address(&) of a given variable.

1 scanf("%d", &magicNumber);

TestingWhen testing your program, it is useful to test values that will run all parts of your code. So for the above if statement, numbers less than, equal toand greater than 9000 would be useful to test the if statement. You should also test, really big and really large, zero and some other stuff.

Returning

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

10 of 77 20/06/11 10:10 AM

Page 11: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 2 3 4 5 6 7 8 9101112131415161718

int function (void);

int main (void){ int x = 0; x = function(); if (x == 3){ printf ("the function returned a value of 3"); } else { printf (" returning inside if statments is bad practice") return DO_NOT_DO_THIS; }

return EXIT_SUCCESS;}

int function (void){ return 3;}

Programmers Tip: Picking the right algorithm or method to solve a problem will speed up your program so much more than introducing littletweaks to add small speed boosts.

Previous Chapter | Next Chapter

COMP1917 Lecture 7, Week 2

CHAPTER 07DEFINITIONSStyle: constants should be represented in all CAPS.used so that small changes to constant numbers can be modified in one line.

123

#define "replace this" "with this".OR#define "THIS" "as this".

ASSERTincluded in the header file <assert.h>.If conditions == 0 (ie. False) then assert 'fails' and the entire program is stopped. *If =/= 0, then assert doesn't do anything.Nota Bene: Like in if, conditioning statement must be done with *double equal signs*. Otherwise, function will fail

12345678

int main (int argc, char* argv[]){ int x = 3; printf ("the assert function will throw an error if the expression it is given is FALSE"); assert(x == 9);// will throw an error during runtime as x does not equal to 9

return EXIT_SUCCESS;}

BinaryBinary numbers, position corresponds to a power of 2.;

| 2^7 = 128 | 2^6 = 64 | 2^5 = 32 | 2^4 = 16 | 2^3 = 8 | 2^2 = 4 | 2^1 = 2 | 2^0 = 1 | etc;Compare this with decimal

| 10^7 = 10000000 | 10^6 = 1000000 | 10^5 = 100000 | 10^4 = 10000 | 10^3 = 1000 | 10^2 = 100 | 10^1 = 10 | 10^0 = 1 | etc;Examples

00010100 = 16 + 4 =20;00010011 = 16 + 2 + 1 =19;00010010 = 16 + 2 =18 etc.;

To double a binary number, simply shift the entire number to the left and add a 0e.g. 20 = 10100,;

40 =2*20= 101000.;Halving is similar. (Analogous to dividing by 10 in decimal)

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

11 of 77 20/06/11 10:10 AM

Page 12: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Testing & StyleClean code makes easy reading = easy error checking

Leap year testing: use a number of test cases that test all paths through your algorithm. Pay attention to boundary values! 0, 1582,4000, 4004, 1199, 1900, 2000 etc.

Use meaningful variable namesSpell correctly, where different spellings exist stick to American.Minimise the duplicationobfuscating c competition! (?)

Magic numbers are bad. Use #defines.You can use variables for storing your magic numbers but then you have to keep track of them. (More testing) Also, it apparently slowsdown runtime. #defines = cleaner.Entering a #define into scanf won't work (for now).

Function as a magic box

A function can be considered a magic box that does crap. Input -> Magic Box -> Outputeg. WW2 Britain -> Wardrobe -> Narnia

A function should do same thing regardless of context (unless it factors in context)eg. the Narnia closet will work regardless of the room it is placed.

Qualitive vs Quantitativequalitative/quantitativecomputers doing lots of stupid things over and overquantitative bagel recipe- how do people make different things with the same recipe(more to the recipe that you can write down)As you move up levels of abstraction, you lose information and you can go from quantitative to qualitativeHigh School = black and white, everything else = shades of greyback to idea of recipes and bagels

who is responsible for the user entering in the wrong thing?functions/rationality: Irrational Treasure/nothing to do with puzzle quest at all.legal input -> eventual legal outputcomputable function = something you can work out using pen and paper

church/turing hypothesis- something about computable functions and turing completeness

Previous Chapter | Next Chapter

COMP1917 Lecture 8, Week 2

CHAPTER 08DATA TYPESInteger Types

int x: (memory to store integer, usually 4 bytes (32bits) but can change. Most Commonly Used)short int x: (memory to store integers, but less memory usually 2 bytes )long int x: (memory to store integers, but more memory, )long long x: (memory to store integers, even more memory is assigned )unsigned int x: (gives memory to store only positive integers)signed int x: (gives memory to store both negative/positive integers)

First bit of the set of numbers is used to indicate plus/minus. i.e. 0 = positive, 1 = negative.

Decimal Types

float x: stores decimals. Consists of an exponent, a sign and a set of significant figures. The exponent simply shifts the position of thedecimal point, making the decimal point unrestricted to a position. This gives birth to the name "floating point" i.e. "float".floating points: assigns certain amount of memory to show where you want to place the decimal point.double x: also stores decimals but uses 8bytes to store data. Double is a float with 64 bits(8bytes).

char: stores charactersBoolean: used to store either a YES or a NO (No = 0, Yes = non zero number)

123

boolean passed = (mark>=50) if (passed) { }

All these different types of data implies that a set of binary numbers can be interpreted in many different ways, so there must be a way to define

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

12 of 77 20/06/11 10:10 AM

Page 13: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

how you want each specific set of binary numbers to be read by the processor.

(the sizeof(int) depends on the system you are using, if it is a 32bit system, it should be 4, if it is a64bit system, it should be 8).NB. there are 8 bits in 1 byte.

Binary - Base 2 Conersion table

Decimal Binary Hexadecimal Decimal Binary Hexadecimal0 0000 0 8 1000 81 0001 1 9 1001 92 0010 2 10 1010 A3 0011 3 11 1011 B4 0100 4 12 1100 C5 0101 5 13 1101 D6 0110 6 14 1110 E7 0111 7 15 1111 F

Hexadecimal - base 1616^3 | 16^2 | 16^1 | 16^04096 | 256 | 16 | 1(Note the similarity to the Binary table:16 = 2^4 | 8 = 2^3 | 4 = 2^2 | 2 = 2^1 | 1 = 2^0)Hexadecimal is represented by numbers 0-9, and letters A-F (where A = 10, B = 11,... F = 15).

Example of hexadecimal conversion

Convert BAD from hexadecimal to decimal:16^2 | 16^1 | 16^0B | A | DHence BAD = (11 * 16^2) + (10 * 16) + (13 * 1)BAD = 2989

ASCII

Previous Chapter | Next Chapter

CHAPTER 9

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

13 of 77 20/06/11 10:10 AM

Page 14: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Binary <=> ( 8 4 2 1 : 4004, 4places 16 bits)

To use -number: -8 ... 0 ... 7, ( 0 ... 15)

ALTERNATE COMMENTING/* and */ can also be used for comments.It is a block comment.The style guide says not to use them. Use C99 style instead (that is using "")Good for quickly eliminating chunk of the code during debugging process.

RETURN VALUEIt is more useful to use EXIT_SUCCESS as the return value, in the successful completion of your main function in your program. EXIT_SUCCESSwill be defined in the standard library on the system you compile your program on, so if the value is ever non-zero, you don't ever have to change it.Use a printf to print the value of exit success.

NUMBERs/VARUABLE NAMESNumbers alone have no meaning. Instead, their meaning is given to them by their context. In programs, we should try to use words with meaningsinstead of numbers.

Names are important. Try to give variable name that is easy to remember and suits its role in function.

VARIABLEs“int x;” sets aside some memory for an integer labelled x. Remember an int is whatever is convenient for the system.

STORING of NUMBERMost computers would store in base 256. Of the four bytes used for an int:...

the first might store 1 or 256^0’sthe second 256’sthe third 256^2’sand the third 256^3’s...

'VOID' in FunctionsFunction may not output any value or input any value or both. This types of functions use 'void'

Function with no input will have prototype ofint x (void) {}

Function with no output will have prototype ofvoid x (int x, int y) {}

Function with no input and output will have prototype ofvoid x (void)

FUNCTIONS MUST BE DECLAREDAn error “implicit declaration of function/variable” just means that you are using function/variable that has not been formally declared yet.Declaration means following:

for function, putting function prototype before the main functioneg int function(int x, int y);

for variableeg. int x;

You should always use double instead of float, to reduce rounding errors.

PLACEHOLDER for DIFFERENT DATA TYPES%d for integer%x for hex number%c for character%l for long%f for float and double%p for pointer%u for unsigned integer

1 double height = 1.84;

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

14 of 77 20/06/11 10:10 AM

Page 15: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

23456

printf (“%f\n”, height);

Hexadecimal numberslong hex = 1234;printf (“%lx\n”, hex);

warning: statement with no effect -> Compiler thinks one of your functions is just a statement. Did you miss some double brackets?

GENERAL NOTESFunctions are useful because they allow you to manipulate chunks of your program at a time

Variables inside functions only live as long as the function does. When it is called, they are created. When it returns, they are removed. The functionin which the variable exists is called the scope.

Scanf() can be used in any function in your program, so can any function.

Previous Chapter | Next Chapter

Chapter 10NEW C FUNCTIONS

sizeof - Tells how many bytes a variable used - i.e. sizeof(x);

Pointer - Acts as a copy of variable address, which can be declared with * - i.e. int *address; and follows by address = &x - which meansthat a variable 'address' stores an address in hexidecimal form of variable x

Logic operator and, or&& for 'AND'|| for 'OR'Nota Bene: & and | has similar meaning but works in different way

SOME TIPS & CONCEPTSSide effect - Though a function with void return (i.e. void funcName (void);) doesn't return anything, it can prints on screen or takes inputdata from keyboard. These are called "side effect."

Clarity - Divide big chunk of code into smaller functions, and don't cram everything in a single line.

Overflow - This occurs when a value too large to be stored by an assign integer is given to an integer variable. Be very careful with overflow,since the compiler doesn't show any error regarding an overflow.

Bitmap FileSimilarly with any other file in a computer, it's a collection of bytes. Values in each pixel can be observed and edited with a Hex Editor.

Header file has the size of 54 bytes.Main array occupies 3*Number of pixels in 24 bit BMP file. 24bit BMP file is called as such as each colour component occupies 8 bits ofdata resulting in total of 3 x 8 = 24 bits of data.

exception is where padding is needed. padding is needed if total pixel number for the row is not a multiple of FOUR. Smallest numberto make this pixel row number multiple of FOUR is added as a padding.In 32 bit extra 8 bit is used to store alpha value or transparency

The very beginning of the array records the bottom & right corner of the image

BMP Header Structure in struct format

One that needs to be changed is marked *

BMP HEADER(14Bytes)

1 2 3 4 5 6 7 8 910

struct bmpfile_magic { unsigned char magic[2]; //File Code: BM(42 4D in ASCII)}; struct bmpfile_header { uint32_t filesz; // Size of the WHOLE BMP File* uint16_t creator1; // Application uint16_t creator2; // Application uint32_t bmp_offset; // Offset where pixel array can be found(basically header size)};

DIB HEADER(50Bytes)

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

15 of 77 20/06/11 10:10 AM

Page 16: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 2 3 4 5 6 7 8 910111213

typedef struct { uint32_t header_sz; // DIB HEader Size(40bytes) int32_t width; //Width* int32_t height; //Height* uint16_t nplanes; // Number of colour planes being used uint16_t bitspp; //number of bits per pixel(24bits) uint32_t compress_type; // pixel array compression uint32_t bmp_bytesz; // size of the raw data including padding* int32_t hres; //Horizontal Resolution(2835) int32_t vres; //Vertical Resolution(2835) uint32_t ncolors; // Number of COlours in the palette uint32_t nimpcolors; // Number of important colours} BITMAPINFOHEADER;

from Wikipedia: 54 byte header of a 2x2 bmp file:

Offset Size Hex Value Value DescriptionBMP header

0 2 42 4D ”BM” Magic number (unsigned integer 66, 77)2 4 46 00 00 00 70 Bytes Size of BMP file6 2 00 00 Unused Application specific8 2 00 00 Unused Application specific10 4 36 00 00 00 54 bytes Offset where the Pixel Array (bitmap data) can be found

DIB header14 4 28 00 00 00 40 bytes Number of bytes in the DIB header (from this point)18 4 02 00 00 00 2 pixels Width of the bitmap in pixels22 4 02 00 00 00 2 pixels Height of the bitmap in pixels26 2 01 00 1 plane Number of colour planes being used28 2 18 00 24 bits Number of bits per pixel30 4 00 00 00 00 0 BI_RGB, no Pixel Array compression used34 4 10 00 00 00 16 Size of the raw data in the Pixel Array (including padding)38 4 13 0B 00 00 2835 pixels/meter Horizontal resolution of the image42 4 13 0B 00 00 2835 pixels/meter Vertical resolution of the image46 4 00 00 00 00 0 colours Number of colours in the palette50 4 00 00 00 00 0 important colours 0 means all colours are important

Start of Pixel Array (bitmap data)

RGB Color Chart

Remember in actual bmp, it is recorded in reverse order so BGR

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

16 of 77 20/06/11 10:10 AM

Page 17: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

GENERAL NOTESTesting Tip - Write a void funcnction (void); to performs code testing with simply using assert command for data comparisons for eachdeveloped test cases. Remember to call test function at the beginning of main function.

Portfolio Attributes - See here. You should put all of the evidences demonstrating these attributes in your portfolio page, which can becreated from your profile page by add /Portfolio to the end of the URL and click Create New Page.

Group Work - If you've encountered problems, don't blame other, even if they were extremely slack Always look at yourself first and try tosolve the situation in a positive and productive way

Previous Chapter | Next Chapter

Chapter 11Complexity, Functions and MemoryCOMPLEXITY & DESIGN APPROACH

Top down design

Break down a problem into smaller problemsBreak down the smaller problems into smaller problems...and so forthWhen applied to computing/programming, this could translate into breaking down a function to solve a problem into smaller functions thatsolve the smaller problems that make up the bigger problem

Function design

"Your function should never be long""If your function goes off the screen it should be split up""Each function should do one thing"

PASSING INTO FUNCTIONSYou can pass functions into functions, but doing this too much causes your code to look messy and clutterede.g. From task 1, you can use int dayOfWeek(int doomsday, int leapYear, month, day) like this:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

17 of 77 20/06/11 10:10 AM

Page 18: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 int weekDay = dayOfWeek(doomsday, isLeapYear(year), month, day);

OR

1 int weekDay = dayOfWeek(yearToDoomsday(year), isLeapYear(year), month, day);

Use of less intermediary value(and using more function call) can result inMessy styleComplexity of having to call function everytime

One action/ line is strongly recommended.CONCLUSION: Do whatever is the most easy to understand and simplistic

GENERAL FUNCTION USAGEWrite good, clear prototypes with relevant data types that tell the reader what is needed to be passed inOf course, the compiler doesn't care about any of this save for the order the data is passed in, and whether or not the data types are the sameThe names of the variables in the prototypes and definitions don't matter- e.g. you can do this:

1 2 3 4 5 6 7 8 91011

typedef int guy;

int protoType(guy A, guy B);

.

.

.

int protoType(guy FredAstaire, guy GingerRogers){//definition}

OR EVEN

123

int protoType(int X, int Y) {//definition}

MORE ON FUNCTIONSIn this lecture it was touched on that functions only use a copy of what is passed in rather than the originalThere are ways to make functions mess with the originals, but you can find that all out later when you get to the project chapters

MemoryMemory

When you look at stored memory it is just a bunch of 0s and 1s that don't inherently carry any meaning other than zero or oneness.For example 8 bits could represent an integer between -127 and 128, or an integer between 0 and 255, or a character.Basically, a bunch of 0s and 1s don't have any meaning until you interpret them as something with meaning, say a bitmap or a string or anumber etc.

Bitmap file formatInformation on how to interpret the data is stored in the header, the data is stored at some memory address (specified in the header) after theheaderThe specifics of the bitmap file format are probably completely unnecessary to know.More information can be found on Previous Chapter

Previous Chapter | Next Chapter

Chapter 12Summary

Code repetition isn't good because you increase the likelihood of mistakes (maintainability)This should be replaced with while loopsGeneral form of while loop:

1 while ((condition) && (count < COUNT_LIMIT)) {

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

18 of 77 20/06/11 10:10 AM

Page 19: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

234

printf ("Comp1917 is awesome!\n"); count++; // do not forget to increment count}

Functions only take a copy of the input and doesn't change the original input

RepetitionRepetition. Referencing. Allowing you to reuse things over and over again.

E.g. in a book - the subtle differences are more pronounced.E.g. Harry Potter. Bad repetition. Repetition without reason.

Why do we need to avoid repetition?

1) To decrease possibility of mistakesforget to change one of repeated part by mistaketype wrong

2) For Clear appearance3) To minimize file size4) To shorten writing time

Repetition in generalWorking towards the code on https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Lectures/Week04/Slides:Repeating

1 printf("*********\n");

in the code twice is not good - if you change it later, you might change one and not the other (maintainability).

What we did was

1 #define LINE "*********\n"

Now we can change them to #'s or anything else easily!

But

1234567

printf(LINE);printf("Chapter 1\n");printf(LINE);

printf(LINE);printf("Chapter 2\n");printf(LINE);

is also repetition

For this we put it in a function.

12345

void drawChapter(int chapterNumber) { printf(LINE); printf("Chapter %d\n", chapterNumber); printf(LINE);}

So in the main function we just need to write:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

19 of 77 20/06/11 10:10 AM

Page 20: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1234

drawChapter (1); printf("\n\n\n"); drawChapter(2);

Bagel recipe. High level of abstraction in recipes."Knead the dough" as a function. This means people can "knead the dough" in different ways and the recipe isn't too detailed. Seeabove code.Repetition - "Repeat with 7 other dough rounds" - the same instruction can be carried out 8 times without repeating it 8 times. It can beeasily changed and is easier for the person carrying out the recipe. (see below - loops)

Loops

1234567

int chapterNumber; chapterNumber = 0; while(chapterNumber <= 10){ // "Asking the gatekeeper" drawChapter(chapterNumber);

printf("\n\n\n"); }

It is forever chapter 0 - we need to change the chapter number as it goes through the loop each time.Add:

1 chapterNumber = chapterNumber + 1;

to the "while" loop.For brevity, this can also be written as:

1 chapterNumber += 1;

or

1 chapterNumber++;

We then change chapters to the bat song. :D

Side note while we were writing the code: Although batCount was incremented in both the while loop and the function that called it (singVersefunction, not included here), it was not incremented twice because the functions only works with a copy of batCount. It doesn't change the actualbatCount. (This does mean that we don't need that line in the singVerse function though.]

Previous Chapter | Next Chapter

Chapter 13Duplication and Repetition

1234567

int counter;

counter = 0;while(counter < value) {do_another_thing;counter++;}

All "while" loops have this general structure.

Note 1: "counter", "value" & "do_another_thing" are just place holders, not literal text.Note 2: You could also have a ">" with a decrementing counter.Note 3: counter++ ---> counter = counter + 1

Or to decrement... counter--

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

20 of 77 20/06/11 10:10 AM

Page 21: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Richard also mentioned another structure which we won't disclose here because, as far as you are concerned, in this course you will use the abovestructure!

Common Faults in "While" loops

1.Not initialising the counter or giving it the wrong value, e.g. counter = 0;

2.Not incrementing the counter and therefore not progressing in the loop, e.g. counter++ or counter--;

3.Not having the correct test, which can lead to what is called a "fence post error" where you are out by 1.

Fence Post Error

Consider the following fence, which consists of 4 section each 1 unit long.

0 1 2 3 4

| | | | | |

To calculate the length of wire needed the calculation would be 4 - 0 units. However to calculate the number of posts required (not including anystays) the calculation would be (4+1) - 0. So you can see that you could easily be short a fence post if you get the calculation wrong.

As a general rule if:

-the counter is initialised at 0 the condition should be "<".

-the counter is initialised at 1 the condition should be "<=".

You can check this with a test case e.g. if you need to calculate the days between two dates look at the result at a few days apart then generalise theresult out to many days apart.

Can you imagine what a loop that goes on forever might look like?

At this stage what Richard was going to show on the screen had to be abandoned due to the "technical difficulties" alluded to earlier so we had totake another tack!

How does a Function WorkRichard made the following analogy. Recently he has been working with a team as part of the Australian Computer Society (ACS) to accreditcomputing courses in other universities. This requires people that are senior and important within the ACS and he has been working with someonethat he holds in high regard who always seems so calm relaxed and unflustered. This is in comparison to himself who is always flustered andmessing about with "stuff". (Or so he says.)

So how does this respected person do it. Well Richard noted that when it became apparent that this respected person needed to book a flight toEurope in a few days time he just picked up his phone, rang his secretary, apparently a very competent person, and asked her to book the flight forhim, i.e. he delegated.

As opposed to Richard (who is obviously not senior enough to have a competent secretary), who would have to interrupt what he was doing, phonea travel agent, book the flight, sort out the details, before he could return to what he was previously doing, by which time he'd forgotten what he wasdoing anyway!!

A function is similar to the respected person's secretary in that the secretary has the detail of the task to be carried out and is competent to do itwithout further oversight from his/her boss.

Properties that functions should have

1. Two functions should be distinct from each other. As a principle in computing you should do things once and once only! Don't repeatyourself. Functions should be discrete, separate and whole, i.e. they are self contained and do the whole thing.

2. A function allows you to reuse code without having to write the whole code out again. As well, if you need to change the code you onlyneed to do it in one place rather than searching for all the instances where it might be used and probably missing one.

3. Functions allow you to break a program into smaller discrete parts which become self contained jobs and allowing multiple personteams to work on a project.

You should appreciate that computers can only do one thing at a time; not multi-tasking! They follow only one path at a time. When a computerprogram is interrupted, while another function does it's job, the program / computer uses a "Frame" to remember where it was.

Frames can have vulnerabilities which have been used by hackers in so called "Stack Attacks", e.g. while the program is off doing a side functionthe frame can be altered to take the program back to some other place where the hacker might, for example, be able to create a "Super User".

Previous Chapter | Next Chapter

Chapter 14

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

21 of 77 20/06/11 10:10 AM

Page 22: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

From Simple to ComplexLet's remember that functions take in stuff, does something to the stuff and spits out more stuff.

For Example: The wondrous(x) function takes one input and (by definition of a function) gives one output.

If x is odd. multiply by 3 and add 1 (3x+1)If x is even, halve (x/2)

If we fed the output of wondrous(x) as the input for the next round, it'd be like feeding a snake to itself. It'd eventually end up in a loop.

Let's say we take 32 as our initial input:

32 is even, so halve to get 1616 is even, so halve to get 88 is even, so halve to get 44 is even, so halve to get 22 is even, so halve to get 11 is odd, so multiply by 3 and add 1 to get 44 is even so halve to get 22 is even, so halve to get 11 is odd, so multiply by 3 and add 1 to get 4etc.

This is an instance of emergence, a system that's far more complex than the sum of it's parts. You never would've guessed that toast is actuallystill a type of bread, so you can put it into the toaster over and over again, you'll get something completely unexpected! (Do not try this near a firealarm.)

What We've Been Learning In CWe started with something simple like a player piano roll. We then added "if", giving a program the ability to make decisions based on anyinformation it had available, a huge step towards allowing computers to be self aware. When we added "while" everything just went crazy!It was almost as if you could write a program that automatically copied out sections of itself.It's unreasonable to deem something impossible, without some ridiculous (usually incorrect) assumptions!For example, our intuition would tell us that many things were impossible on the 4004, but we wouldn't know for sure unless we actuallytried every last one of the 16^16 different programs. Many people thought it'd be impossible for there to be a 4004 Quine, but apparentlyAlexis wrote one.

Side Note: Richard did his thesis on something regarding this kind of thing. He found that you could prove the properties of certain combinationsand it'd significantly reduce the number of cases you have to check.

Nested LoopsTree diagrams can be used to demonstrate a programs structure: loops within if's, if's within loops, while's within if's within loops of while's!

Richard: Looking at flags! They're like a function call….oh, uh the New Zealand girl I though she sounded American…<shrugs> doesn't like New Zealandflag being identified as Australia…:P

To make sure that our loops within loops, or nested functions won't create an infinite loop as in the wondrous function, we should always test ourfunctions.

Some Suggestions To Do This

Counting how many characters we are printing? Good idea, but we are changing the functions...How about a global counter? "no, we never want to... in case of multiple global counters running at same time"

THE SOLUTION: simply print this is what it should look like:

###########################################################################

and then run the function! :D then u can always test it! :D Be ingenious! Its not the best solution, but it WILL work! and the screens gone black again.. aswith last lecture.. will write everything on the blackboard!

EXAMPLE OF NESTED LOOP (IN printLibya function)

1 2 3 4 5 6 7 8

#define WIDTH 15 #define HEIGHT 5 void testLibya (void);void printLibya (void); int main (......) { void testLibya (void)

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

22 of 77 20/06/11 10:10 AM

Page 23: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

9101112131415161718192021222324252627282930313233343536

void printLibya (void) return EXIT_SUCCESS; }

void testLibya (void) { printf ("this is what the flag should look like!"); printf ("###############"); printf ("###############"); printf ("###############"); printf ("###############"); printf ("###############"); } void printLibya (void) { int row = 0;

while (row < HEIGHT) { col = 0 while (row < WIDTH){ printf ("#"); col ++; }

printf ("\n"); row ++; } }

row and col are common abbreviations in Computer Science! :D

More powerful function could be created by combining if function with while function, as shoen below in printpixel function.

1 2 3 4 5 6 7 8 910

eg. void showPixel (int col) { if (col < (WIDTH/3) { //note magic number three, we should rehash pixel = 'g'; //define this, but this may cause errors if } else if (col < (WIDTH/6)) { // flag width isnt divisible by 3 cleanly pixel = 'w'; } else { pixel = 'o'; } printf ("%d", pixel);

in our labs this week, we will be drawing flags like this! How exciting! we dont really want too many levels of loops, jump anything more intoanother function! :D NOW FOR A BREAK! END LECTURE 14! :D

Machine Code: FunctionsRichard also discussed how functions can be used within machine code. The function must have:

An input stored into a specific location within the function (not enough registers)A frame (holds return position and pre-function register values)A constant area of memory saved only for the functionReturns value through a register

Previous Chapter | Next Chapter

Chapter 15About Server

IP is a 4byte data. Dot separates each byte.

How Server Works

Client(your computer) sends request using HTTP(a protocol)Server receives request and send the request back(telnet can visualise this process)There is a header which tells client more about 'message' is server is about to send.

The 8004 series microprocessor !Registers: IP, IS Two general registers: R0, R1

0 Halt1 R0 = R0+12 R0 = R0-13 R1 = R1+1

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

23 of 77 20/06/11 10:10 AM

Page 24: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

4 R1 = R1-15 R0=R0+R16 R0=R0-R17 Print R0 as an unsigned int

Two Byte Instructions

first cell contains the instruction, second is called the data cell

8 Jump to <address> if R0 !=0 data cell contains the address to jump to

9 Jump to <address> if R0 ==0 data cell contains the address to jump to

10 <value> -> R0 load the value stored in the data cell into R011 <value> -> R1 load the value stored in the data cell into R012 R0 -> <address> write the contents of R0 into a memory cell. The memory cell used is the one pointed to by the data cell13 R1 -> <address> write the contents of R1 into a memory cell. The memory cell used is the one pointed to by the data cell

14 R0 <-> <address> swap the contents of R0 with the contents of a memory cell. The memory cell used is the one pointed to by thedata cell

15 R1 <-> <address> swap the contents of R1 with the contents of a memory cell. The memory cell used is the one pointed to by thedata cel

Additional one byte instructions|

16 Ring the bell!17 Print R0 as an ASCII character

NEW MICROPROCESSOR! Series 8004openlearning.cse.unsw.edu.au/Comp1917/2011s1/8004 Now with 256 bytes of storage!

We now want to produce the 'wonderous' function from last lecture:The wonderous function has ONE INPUT and ONE OUPUT with condition

"If input is odd number --> multiply by 3 then add 1""If input is even number --> divide by 2"

Program lay out should be like this

Odd/Even Filter to select between odd and even functionsOperation Section

One for odd: Which will do "number x 3 +1"One for Event: Which will do "number / 2"

With 256 cells to play with, we can designate section for above mentioned various parts of the program. So we can have main function in first 50addresses, other functions in next 150 addresses and finally last 56 can be a 'frame' for storing numbers to be used during processing.

SO: The program suggested is:

10 6 11 1213 200 12 201 (writing where we are up to in 200, and the input to 201)10 0 9 100 (Natalia has now frozen/paused (our main function))

--> jump to address (&) 100 HINT: in binary all odd numbers, the last bit is a 1... ;) Richards way to detect if its odd BUT we wont use that, lets usea suggestion from before (sorry friend, i missed your name)

14 201 2 ...

..........

and now this is completed as people were getting restless! now we must return! Pass the information back in register 0! (like in gcc) (C dec L (???))so simply (having rewritten the position into the correct places in the functions position):

8 position 9 position

note: the function COULD do malicious things to the registers! Also with our current setup, we shouldve saved R1 and reloaded it before the end ofthe function, so there isnt any gunk there from the function (side effects) i.e. returning your room back to how it was before your started!

Previous Chapter | Next Chapter

Chapter 16

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

24 of 77 20/06/11 10:10 AM

Page 25: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Notes about asking questions:

Search for already open relevant threadsMake post titles relevantRead the FAQ first as wellBe courteous, have good netiquette: hands off capslockFeedback to answers givenDon't submit just hours before due

Assignment management:

Upload early, upload often, use it as a backup mechanismproject management: think of potential disasters as adversaries and plan against them with contingenciesRead : Marking in the CSE labs. unit testing could not work while final marking could

Being a good programmer is not about knowing specific syntax It's a state of mind, almost.

Plan:

RisksPotential dangersHow to assess progress.How to check the solution answers the right questionSolve the task, don't try to outsmart the task. "The Spec is King"

New notes:

openlearning user<->task progress bars"It's always hardest before the dawn" But if you're having too much trouble, last day to switch to comp1911 is Thursday 31st Mar. 2011

Learning about syntax specifics vs learning about assessing correctness and coded to spec.Proving assumptions are accurate

Correct code is written:

In an apparent fashion: the function should be obvious and clear. Time required for others to read/understand the code should be minimal.Errors can be introduced by others who are trying to interpret unclear code (the chance of these errors occuring is kept to a minimum whenclear code is written).Good code should be intuitive to read (it is better for code to be clear and concise than short and clever)The best written code is that which is most simple and easy to understand

Testing is done on a sample of inputs: very hard to ensure 100% of valid input produce valid output

Testing:

testing your own code can be dangerous

2) black box testing:

examines only the inputs and the resultant outputse.g; an outsider without access to source tests your function

3) white box testing:

examines the process of converting inputs into their resultant outputse.g; tester is separate from coder but has access to source code

4) unit testing:

emerged about 10years ago or soprograms are made of functional 'units'each unit is tested to ensure they work as expected. this increases the likelihood of the overall program working to spec, even as the programgrows in complexity beyond normal overall testingtests should also include 'non standard' inputs (i.e. those which are not expected)By controlling complexity:

tests can be more rigorouserrors are narrowed down much closer to source if identified. speeds up identification and hence resolutiontests can be added as the program grows, which grows a library of comprehensive tests to run on the end product.splits the overhead of testing across all component/elemental units: easier and more likely to have testing adopted.

Standard documents:conventions agreed upon to allow for many people to collaborate on units to write complex programs and tests.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

25 of 77 20/06/11 10:10 AM

Page 26: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Wondrous8004 example standardlocations for functions:050 Half100 next number in sequence150 isEven200 a function to print a term and a space afterwards

Testing 8004

We have to know where the functions are going to be in order to test themWe also need to know their frame (where they store and access their data)From these two points, we can see the importance of maintaining standards (such as those listed above)

Practise coding at least three hours a week!

REMEMBER: When using the discussion forum, make sure you do not ask the same question. Use the "Search" function that is available in yourbrain, first.

REMEMBER: Always upload your assignment to the website as backup, since only the last submission BEFORE DUE DATE will be marked soyou can keep updating your workspace, you could use the "run basic test" function to see how you're going too!

Blog reminder: Post what went wrong when you were trying to finish up your project.

Previous Chapter | Next Chapter

Chapter 17C and Machine CodeC programs are convenient to write/create due to its power, but the rules governing C programs are very complicated. Machine code programs arevery tedious and challenging to create, but the rules governing them are quite simple. We can write any program in either, but machine code willproduce much more code.

C and machine code are more tightly bonded, compared to other programming languages and this is the reason we learn the fundamentals ofmachine code, and not just C.

Compilers converts what we write to something the microprocessor understands. Most computers use x86 chipset, they understand x86 instructions.

C and machine code can be related via abstraction. This means that C code is a higher level of abstraction than machine code. Similarly, theabstraction can go higher and lower:

Above C: pseudocode (everyday language code. e.g. display the number 6, is equivalent to printf("6"); or some variant).Below machine code: transistors, logic gates, electrical impulses, etc.

Most obvious relation between machine code and C we have come across so far is a function. Functions can be defined and called in machine code(using frames) just like they can in C. Functions are useful when considering abstraction; low down, they are highly detailed, but higher, they arenicknamed, making it easy to deal with.

Core learning module up until now-> Flow Control (procedural abstraction):

Sequential composition: Putting lines of code or functions after one another and C executing them one at a time, from top to bottom.Functions: Providing abstraction to massive chunks of code by using a very short amount of code to call and execute large amount of codefrom elsewhere.Selection: Using 'if' statements to direct code execution along a 'branch', depending on if a condition is met.Iteration: Automatically repeating the execution of code until a condition is met.…and that's it; everything else is just 'syntactic sugar'

Core learning module from now on-> Data abstraction.

Data AbstractionDevelopment of programming languages has mainly been channelled into improving and reinventing data abstraction, not flow control.

Increasing the complexity of flow control in your program, usually means a simplified level of data abstraction. The vice versa also applies.

Example

When we print a statement, we can print each individual letter like in machine code: (load number, convert to ASCII, print, etc)

But this is bad, as user data and control data are getting mixed together. Programs should always separate the 'what' from the 'what is being done tothe what'. This means that control data should be separated from user data (Richard gives the example of the Cap'n Crunch whistle). Failing thismeans that our programs are vunerable to attacks.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

26 of 77 20/06/11 10:10 AM

Page 27: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

The alternative is keeping the string in a separate location; going back to machine code, have load a letter (R0) whilst keeping a counter, (R1),which increases (corresponding to moving to the next letter). The program must remember that 0 means halt.

A string is esentially a group of chars.

Another example

Store all the characters of the string in a section of memory.1.Store the start address of the string in a frame.2.Create a function that prints out the contents of adjacent memory addresses and uses the frame to determine the start address of the string.3.Call the function.4.

The main reasons why this method is more effective than just doing it all in one 'blob': If you wish to change what is printed, you just change thecontents of the memory addresses storing the string, instead of also changing the method of printing the characters. You have made a function andthis allows for the printing of multiple strings (supporting "DRY").

Why using a pointer?

Because 2 strings may have the same name. For example, it allows identification of particular people or group of people by their positionsinstead of their names as 2 people can have the same name.

Variables and pointers have pros and cons.

Variable pros:Simpler to implement.Change of memory addresses is not an issue.

Variable cons:Usually deal with copies of the variable and not the actual thing.

Copying the variable many times builds up memory usage.Pointer pros:

Being able to deal directly with memory (greater control over data).Directly change the contents of variable using a small amount of data, instead of copying the contents of variables everywhere.'Return' multiple values from a function.

Pointer cons:Risk of doing damage to the wrong memory address(es)(buffer overflow).Generally more complicated to implement.Changing the address a pointer points to and not changing it back.Can incur complex errors.

Syntax&: location or address of variable (data) in memory*”: (a pointer) refers to the contents of the address that a variable may hold%s: format character for printing a string.%p: format character for printing a pointer. When gcc sees (e.g) message, it really means (e.g) address 100. The contents of this address is apointer to another address, which contains the data Each variable then has 2 bits of code; the address and content Functions are stored inmemory up the top, while the data is stored down the bottom

Syntax examples:

char * message = tree; sets aside (for this example) 5 bytes of memory, ‘t’ , ‘r’ , ‘e’ , ‘e’, 0 (terminates). We need to refer to that area ofmemory, so we use pointers.char * => something that points to a charaterprintf("%s\n", *message); prints out the string that message refers toprintf ("%p\n", &message); prints out the address of messageprintf ("%c\n", *message); prints out the contents of where the pointer of message is pointing to (in this example, t)

Note: lecture continuous on the topic of strings in chapter 18.

Previous Chapter | Next Chapter

Chapter 18Revision of StringStrings are a data type which treats a collection of characters as a single thing.They are represented by a pointer to the first element.

In C, this is:

1 char *message = "You are awesome!";where:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

27 of 77 20/06/11 10:10 AM

Page 28: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

*message will give you the value of the first character of the stringmessage will give you the address of the first character of the string&message will give you the address of the address of the first character of the string

To retrieve the entire string, C will find the first character and keep fetching the characters in sequence until it reaches a null character(ASCII: 0x00)If you want to get printf() to treat a pointer as a string, use ~%s. You can retrieve the nth byte of a string (0 indexed) by using message[n].

printf's first argument is a format string, which tells C how to represent the data you give it.

strlen() and string.hstring.h is a C library which provides functions to manipulate strings.

1 #include <string.h>

The function strlen() takes in a pointer to a string and calculates its length. We can make our own with the following code:

1 2 3 4 5 6 7 8 910111213

int stringLength (char *start) { int length = 0; char *pointer; pointer = start; while (*pointer != 0) { length++; pointer++; } return length;}

which increases the pointer until it points to a null character, counting how many addresses it went along.Alternatively, you can use:

12345678

int stringLength (char *start) { int length = 0; while (start[length] != 0) { length++; } return length;}

which, rather than altering the pointer, iterates over the individual bytes in the string (referring to each with its position relative to the start of thestring) and checking for null. This is similar to the first example, except rather than directly modifying the pointer, it modifies a counter variablewhich is "added" to the pointer when the value is being fetched. This method of iteration has the advantage of being independent of the length ofeach element.

What if we wanted to include a NULL character in our string?

The disadvantage of using a 0x00 character to represent the end of a string is that it means we cannot store that character in the data. It introduces asecurity flaw- the data itself is allowed to subtly control how it is processed.

To illustrate this problem, back in the day, telephone companies mixed payment information with sound information in phone calls to controlinformation about charges in frequencies which you wouldn't expect to ever be reached. There was a Captain Crunch cereal toy whistle, however,which was capable of mimicking these signal frequencies. Consequently, you could get free calls by playing the right tune on the whistle.

In computing, mixing control data with user data is one of the main causes of security flaws, as it can introduce errors and allow a user to takecontrol of the program.It is important to create a distinction between your program and your data.

Other string implementations instead store the length of the string in a separate piece of memory This has the disadvantage of using more bytes, andplaces a restriction on string length, but allows for greater control and security, the full range of 256 different bytes and provides efficient access tometadata about the string's length.

Strings and CharactersIn a program, characters are denoted by single quotes, and strings are denoted by double quotes. If you have "Tree" in your program, Cimmediately sets aside 5 bytes of memory, loads the data into it and returns the pointer to the first address, whereas if it were 'T', C recognises it asa single character, loads it into memory and returns it.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

28 of 77 20/06/11 10:10 AM

Page 29: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Strings are stored in an area of memory that is write-protected, which means you cannot change them directly.

ArraysAn array is a mutable set of objects of a predefined length.

Arrays are initialised as follows:type foo[n];where type is the data type being stored in the array, foo is the name of the array and n is the number of items in the array.For example:

1 char message[42];

creates a character array with 42 elements.

Arrays are pointers to the first element of the array, and members are stored next to each other- one after the next, similar to strings. This is possiblebecause the type of each element is already known, so there can be a fixed amount of memory set aside for it.A side effect of this is that when an array is passed into a function, the function has direct access to the data in the array, as the address, not the dataitself, is copied and given to the function.

To access a member of the array, use foo[n] where foo is the name of the array, and n is the index (or number) of the element in the array you wantto use.

You can, for example, make a mutable string using arrays by making a character array and loading a character into each member sequentially,terminated by a null byte.

Arrays are often iterated over. This can easily be done using a while loop by keeping and incrementing a variable which refers to the index of theelement the loop is working on. The following code calculates the number of days in the first 4 months of the year by iterating over the elements ofthe array and adding them to a variable.

1 2 3 4 5 6 7 8 91011121314

#define NUM_MONTHS 4... int days[NUM_MONTHS]; days[0] = 31; days[1] = 29; days[2] = 30; days[3] = 30; int pos = 0; int sum = 0; while (pos < NUM_MONTHS) { sum = sum + days[pos]; pos++; }

Be careful with this! Arrays don't keep information about their size, so you can easily go over the end of the array. This is known as a bufferoverflow.

In the final exam, you'll lose 5 marks for each buffer overflow you make.

Previous Chapter | Next Chapter

Chapter 19 (Extension Lecture)By the NSBs of Wed18NSBHS

RevisionSystems are defined by rulesRules are simpleComplexity in a system rises from the interaction of these rules.The complexity of a system increase with new interactions between each rule.

sequential doesn't do muchselection allows us to choose between more optionsloops allows us to do even more things at once!

Hence, it makes C awesome enough to do any problem (Turing Complete) - (except toast, Chapter 00)As such, simple rules can create complex things.

For example, 3D Chess or Richard-Tac-Toe

Richard-Tac-Toe UpgradeThere are 3 shapes: Squares, Circles and Triangles.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

29 of 77 20/06/11 10:10 AM

Page 30: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

They can be shaded, solid or openThe players take turns placing pieces (each piece can be of one, two or three of the same shape (e.g. 3 shaded triangles, or 2 open circles))You can't play the same piece as the opponent in the same round.To win, the attributes of colour, shape and number, must be either the same or all different.e.g. 3 shaded triangles, 2 solid triangles and 1 open triangle will win

Number: 1,2,3 - All differentColour: open,shaded,solid - All differentShape: triangle,triangle,triangle - All same

richard plays the game!... looks very devious as he tries to predict the enemy... and wins and I don't even geddit...

MultiplicationYou can represent multiplication as shapesDistribution rule:

(a+b)(c+d)

=ac + ad + bc + bd

You can use chickens and eggs as a and b for example. (looks funny and you can't use them well)

(3chicken + 2egg) * (1chicken + 1egg)

=3chicken^^2^^ + 2(egg)(chicken) + 3(egg)(chicken) + 2egg^^2^^

however, we get a proliferation of terms but we can't collapse themordinary numbers can be formed into a single entity because they can be collapsed into like termsIn some situations, this can not be so. For example:

(2 + 3i)(1 + 4i)

= 2 + 11i + 12i^^2

= 2 + 11i - 12

= -10 + 11i

Because there are two numbers (11 and -5) we can plot them on a graph as (-5,11)

Wondrous numbers have simple rules, but can form a complex sequenceThe simple rule is x = x2 + c and we assume the input is x and all values in this (x and c) hold two numbers (#,#).We assume that the first input of x is 0 and c is a constant. The example used in the lecture was this:

x = 0^^2 + (1,1)

x = (1,1)

x = (1,1)^^2 + (1,1)

x = 1 + 2i + i^^2 + (1,1) (the second number is the coefficient of i)

x = 1 + 2i - 1 + (1,1)

x = (0,2) + (1,1)

x = (1,3)

Special Picture of a FractalFractal: Interesting things that have similar levels at different abstraction levels, no matter what, however you zoom in, using incredibly hugenumbers.It's like a beach.

To measure the length of the beach, you can just use a tape measureHowever, this will not be accurate because there are tiny cracks and turns that the map doesn't showThe more you zoom in, the more cracks and turns you encounter.

It's also like abstraction levels in programmingYou zoom in one level, it's CYou go deeper, it's machine codeYou go deeper, it's logic gatesYou go deeper, it's transistorsYou go deeper, it's atomsYou go deeper, it's subatomic particles...

Number Plane with a picture centred on (0,0) [Generated by x2 + c]Points on flickery get really big then really small.Points that take a while to step out are coloured yellow

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

30 of 77 20/06/11 10:10 AM

Page 31: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

It's a fractal! That is, interesting patterns by taking in few rules and get something incredibly complex.MANDELBROT SET is one of the most famous fractals, which is what we will use for the lecture.

Mandelbrot SetCSE Visual (user/pass: beat/eggs)Set generated by iteration a function, causing a series of flashing frames!It is an example of how a simple rule can create a complex thing. It is also an example of self-similarity.The Mandelbrot Set uses the x2+c function.This can be used to find the coordinates of numbers where the reiterated value does not increase to infinity i.e. the output of a functioneventually loops. If a color is assigned to however many times it takes for a function to reach that 'looping point' then a visual representationis created.Another example of a crazy thing created by simple rules is Sierpinski Triangle which can be generated by:

1. Take 3 points in a plane to form a triangle, you need not draw it.

2. Randomly select any point inside the triangle and consider that your current position.

3. Randomly select any one of the 3 vertex points.

4. Move half the distance from your current position to the selected vertex.

5. Plot the current position.

6. Repeat from step 3.

Web ServersWorks by returning data when requested by a browser (a whole lot of data after requesting it, including images)Browser interprets data (image!) and prints on pageTelnet time!

telnet www.cse.unsw.edu.au 80

Trying 129.94.242.51...

Connected to albeniz.orchestra.cse.unsw.edu.au

Escape character is '^]'.

GET /~cs1917/images/icon.bmp HTTP/1.0

<LOTS OF SYMBOLS AND QUESTION MARKS>

Connection closed by foreign host

Bitmap file is known as BM

Upcoming Lab Work1. Sample web server which listen to internet. When a browser requests a page - it calls a C function to print that page out across internet. W

2. Make a function that will print a bitmap image. Something similar to a flag.

Task 2 in PairsListens to the internetGenerates a page after a web browser request using C!Will need to work with Lab partner to modify function that will print a 400 x 400 image of pixels. Each pixel will work out whether it is inthe Mandelbrot Set or escapes the function. Returned tile will be the Mandelbrot Set.We will be provided with one for us to browse.

Previous Chapter | Next Chapter

Chapter 20Task 2 Advices

Object: To generate image drawn from Mandelbrot set (400 x 400px) given co-ordinates of centre and zoom level

let's suppose drawing 4x4 instead:

_ _ _ _

|_|▄|_|_|

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

31 of 77 20/06/11 10:10 AM

Page 32: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

|_|_|_|_|

|_|_|_|_| = 16 squares

|_|_|_|_|

Take shaded square; how to know how much of it is shaded? Keep zooming, zooming; could do so infinitely and still not know exactly. So youcan instead pick an arbitrary spot (centre), find what it is and shade whole pixel that same colour. If image is 4x4, coordinates of shaded pixel is(1.5, 0.5) (to centre).

Now if we zoom in on the whole square too, it'll look like:

_ _ _ _

|_|_|_|_|

|_|█|█|_|

|_|█|█|_| = 16 squares

|_|_|_|_|

Centre of this pixel is same, however as we zoom in, width of each pixel halves - so 0.5 units is the width of the pixel. But since the point we pickedbefore is just a centre point (cannot be used for comparison), it actually becomes as shaded above (centre four).

Expansion on zoom

If zoom = 0, then pixel size = 2-0 = 1 (therefore pixels are 1 unit wide). If zoom 1, then size = 2-1 = 0.5 units. For zoom 2 width is 0.25 etc. Browserzooms for us, all we have to do is work out centre and find colour

How to output BMP

Refers to Libyan flag server. While loop, step over points and when you figure out how to colour it, just output to BMP.

Structure of bitmap

54 bytes header, 3 bytes for each pixel (BGR), padding at the end of each row to make number of bytes in row multiple of 4, and final padding atend to make total number bytes multiple of 4.More Detail can be found around Chapter 11 & 12

Write Pixel to The Server

char pixels[50];

write(clientSocket,pixels,50);

OR

write(clientSocket,pixels,sizeof(pixels));

Can also choose to output each pixel individually, do header in chunks and so on. Each pixel is 3 bytes (in order of BGR).In header, size of file in bytes = WIDTH * HEIGHT * 3 (each pixel = 3 bytes).

Array collection elements of same data type. If we're storing colours, R G and B are representing different things, so they don't belongtogether in an array.

Last part of task: print out Mandelbrot as series of pixels, originally figured out if in the set or not, so black/white (boring). But not alwaysclear if a point is actually in the set or not; if further than 2 outside Mandelbrot, it has escaped; but if within, you can never be confident if it'spart of the set or not (regardless of how many iterations you've gone through). So keep iterating a point X number of times, depending onhow many times it's iterated before it escapes the set, colour it differently.

e.g. make R=G=B = NUMBER iterations (shade grey)

Previous Chapter | Next Chapter

Chapter 21If you need help with a library function, just say "man function". In which case you might be told to use "info function" instead.

Previous Chapter | Next Chapter

Chapter 22Richard's Server has a bug:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

32 of 77 20/06/11 10:10 AM

Page 33: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

How to debug:1. Stare at it and changing random things and hope it works? (not a nice choice but most people in the classroom do that)2. Richard's Suggestion: tears the code into pieces, then insert printf everywhere to see what is going on.

Richard is debuging:Insert printf to see whether the function has been called or not (it has been called)fix the Server to serve bmp rather than pngShould use "_" rather than "-" because of using the old version of Server

Richard's conclusion on debugging:One little error will screw the whole thing!What we should do is we should insert printf into the middle of the code to see whether things are working

Think rationally and don't feel stress The whole process : insert printf, confirm that the function has been called, so it should return an image,maybe the input is wrong, yes it does! because we are using the old version!

New C SyntaxStoring RGB as Array?

Some student asked that whether we could store the RGB value in an array of three. The answer is yes you can but you shouldn't do that, it isdangerous and not good.

Reason:

Conceptually it does not make sense because an array is a structure which is expected to contain a sequence of same type of data. It itexpected to add things to the array but if you store the RGB values, adding things doesn't make sense.

If you want to group related things together, you can use a structure called struct.

Struct

A struct is something like this:

struct {50, 25, 17}, it can contain as many thing as you want, but once you set up a struct, you can't add things to it.

struct is a compound data type in C as well as array, they can be used to join simple things together. When you use compound structure, thingswould become interesting because for example you can set up a struct contain an array which contain another struct, etc.

typedef

typedef is similar to #define, it is a shortcut trick to declare something. eg. typedef unsigned char intensity; then when we run the code, whereverthere is a word "intensity", it will be changed into unsigned char. However, it is different from #define because typedef is only used in substitutingtypes

another example of typedef:

1 typedef char array[10];

then the next time if you want to declare another array with 10 items in it, you could just say:

1 array newArray;

it is the same as:

1 char newArray[10];

Combining typedef and struct

we can write our code in this way:

12345

typedef struct _color{ int red; int blue; int green;} color;

then we can declare our own variables and assigns values to them in this way:

123

color pixel;

pixel.red = 10;

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

33 of 77 20/06/11 10:10 AM

Page 34: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

45pixel.blue = 15;pixel.green = 0;

or alternatively:

1 color.pixel = {10, 17, 12};

note: we use the word "color" here instead of "colour" because we need to standardize it. Since computing is dominated by America in the earlydays so we should use American Spelling to make sure your programing can be used globally.

PS: you should set up your own standard(in this course, follow the style guide)so that when you declare a variable, you don't even think of choosingwhich naming system but doing it without hesitation.

last syntaxthe opening of the Pandora's box:

we can now use all of the functions in the following libraries:(google all of the function or look them up in the manual)<stdio.h> : snprintf() is a good one (the 'n' in the name means save), or fprintf()<stdlib.h><math.h> (exp2() is a particular good one for task2)<string.h><limits.h>

some interesting functions

strtold (convert string into long double)atoi (convert string into integer)

Previous Chapter | Next Chapter

Chapter 23 (Lecture 24)RiskHumans are bad at risk

Management decisions but getting it wrong

For example people put elaborate locks on the front door but forget to lock the back door

Humans are bad at unlikely but catastrophic events

Why do people live on the Californian fault line?

Movie Armageddon – Hollywood spent more money making this movie than governments spend on research about the problem

Dont worry about everything - worry sensibly

Spend lots of money on one thing but not the others

Logins with 2 Factor ID ... RSA Keys

Put lots of money on the 2 factor but $0 in staff training and social engineering attacks

Risk in Computing

printf or sprintf to limit length low prob that you get it wrong.

Shades of grey effort of risk

Human intuition is crap at dealing with high impact

Just understand what the important things are

Estimate pieces of toast - Form of risk management

Hi probability - too hard to solve / don't understand problem Even if I know how to work it out I could get the wrong answer even if 1/100 chanceof getting it wrong

If probability is low then you could just ignore that

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

34 of 77 20/06/11 10:10 AM

Page 35: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

If it is non trivial then i will need to put more effort into that

If i get it wrong a space shuttle could explode

Testing strategies to mitigate risk of error

One airline was taking off from Sydney Airport - pilot miscalculated the weight of the baggage by leaving a digit out, which is a factor of ten. Thesupply fuel with the amount of thrust that they need to leave the runway - cleared the fence by just a bit

Example of extreme failure of systems Someone typing in the weight wrong will happen

This is what Richard call Scoping out the problem or Being an Engineer

Writing software that will help us sensibly deal with errors that may or may not happen

Low impact - too too long to write etc

Hi Impact - components don't work etc

Previous Chapter | Next Chapter

Chapter 24needs to be filled in

much, if not all of this lecture was spent describing the game. for fun and adventures, please look elsewhere.

Previous Chapter | Next Chapter

Chapter 25Stacks - DataStructureThink of it as a Pringles

You eat from the topYou can add something on the topYou can see what is on the topbut you do not necessarilly see what is in the middle

Stack

First in last out (Computing Language)

When main freezes it stores a frame (mainframe)

What does stack data structure store?

what it will do nextvalues of variablesreturn address of the function that main called, is main itself

Stackframe

where you store frames in stacks

Function to request memory (in bytes) from computer

malloc (memory allocation)

eg malloc(100);

char *buffer; (buffer is pointer to a char)

Calling & Returning Functions

Calling a function

1. Put parameters into frame (on the stack)2. Put return address into frame3. Jump into start of function4. Save registers5. Set memory for local variables

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

35 of 77 20/06/11 10:10 AM

Page 36: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Returning

1. Releases memory for locals2. Releases registers3. Restore old sp4. Jump to return address

Previous Chapter | Next Chapter

Chapter 26Memory Management Commandsmalloc()

123

#include <stdlib.h>...<type> *<pointer name> = malloc(<bytes to allocate>);

malloc() stands for Memory ALLOCation and it allocates memory from the heap at runtime.

Returns a pointer to the memory that has been allocated OR a NULL pointer if memory has been unsuccessfully assigned.The memory allocated does not get reallocated automatically when not in use, rather it waits for free to reallocate it. malloc() should beavoided unless you really need it.

Protip

1 malloc( sizeof(char) * 9001);

Allocates room for 9001 chars. Yay! No thinking :D

Protip

Best times to use malloc

Loading a file of unknown lengthReceiving input of unknown lengthSaving memory (Only allocates the space you need)

free()

123

#include <stdlib.h>...free(<pointer to dynamically allocated memory>);

free(), as the name suggests, frees up the memory allocated by malloc. free() automatically knows how much memory is allocated by malloc()(heap manager).

This routine should be done for ALL malloc'd/mallocated memory after the program has finished using it.free() does not guarantee that memory allocated by malloc() is going to be zeroed out which may result in security issues.

Richard’s Example

1 2 3 4 5 6 7 8 9101112131415161718192021

int square(int x) { //print out memory location of integer x printf("x is at %p\n", &x);

//create a pointer to a char char *buffer; //allocate space for 9001 chars, buffer = malloc ((sizeof(char) * 9001));

//This is not part of Richard's code, merely an error checking method //check if memory can be allocated, malloc() returns a null pointer //if memory cannot be allocated if(buffer == NULL) { //do error handling stuff }

//assign 23 to third member of buffer and print out address buffer[2] = 23; printf("b[2] = %d\n", &buffer);

//a little housekeeping

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

36 of 77 20/06/11 10:10 AM

Page 37: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

222324

free(buffer); return x * x;}

Aleksanders' note on free/malloc

The memory allocated does not reallocate after the program closes, leading to memory leaks and possible security issues.

With the exception of some special-purpose or very simple operating systems, and ignoring things like shared memory, operating systems aredesigned to recycle the memory allocated to a program when that program ends.

The main reason you should free() is because if your program runs for a long time leaking repeatedly, its memory consumption gets much largerthan it needs to be. For reasons I don't think are important at the moment, free()ing memory isn't guaranteed to let other programs use that memory,but further malloc()s by the same program will have access to it.

Also free() is not guaranteed to zero out the memory you have freed, so it doesn't give you any security guarantees either.

Previous Chapter | Next Chapter

Chapter 27Abstract TypeIntro

The program will be Abstract typeAn example, a USB stick is abstract type, it can be stuck into any PC and it would workAlthough USB manufacturer never spoke to PC manufacturer

This. is. A B S T R A C T I O N.Insides of USB is irrelevantThe interface is important

Approach the task similarlyThe abstract type is the reasoning behind the capitalised *.c file.Since spec is not complete, build your game to work however you want, but it will need to be altered to spec.

What's an abstract data type?

You're well acquainted with data types by now, like integers, arrays, and so on. To access the data, you've used operations defined in theprogramming language for the data type, for instance by accessing array elements by using the square bracket notation, or by accessing scalarvalues merely by using the name of the corresponding variables.

This approach doesn't always work on large programs in the real world, because these programs evolve as a result of new requirements orconstraints. A modification to a program commonly requires a change in one or more of its data structures. For instance, a new field might be addedto a personnel record to keep track of more information about each individual; an array might be replaced by a linked structure to improve theprogram's efficiency; or a bit field might be changed in the process of moving the program to another computer. You don't want such a change torequire rewriting every procedure that uses the changed structure. Thus, it is useful to separate the use of a data structure from the details of itsimplementation. This is the principle underlying the use of abstract data types.

Here are some examples

stack: operations are "push an item onto the stack", "pop an item from the stack", "ask if the stack is empty"; implementation may be as arrayor linked list or whatever.

queue: operations are "add to the end of the queue", "delete from the beginning of the queue", "ask if the queue is empty"; implementationmay be as array or linked list or heap.

search structure: operations are "insert an item", "ask if an item is in the structure", and "delete an item"; implementation may be as array,linked list, tree, hash table, ...

There are two views of an abstract data type in a procedural language like C.

One is the view that the rest of the program needs to see: the names of the routines for operations on the data structure, and of the instances ofthat data type. * The other is the view of how the data type and its operations are implemented. C makes it relatively simple to hide theimplementation view from the rest of the program.

Implementation of abstract data types in C

In C, a complex data type is typically represented by a pointer to the information stored in the data type. A C function can pass the pointer to otherfunctions without knowing the details of what the pointer points to. One may also use parts of a program that have been separately compiled. Allthat a part of a program need know about functions it calls is their names and the types they return.

Thus, the convention in C is to prepare two files to implement an abstract data type.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

37 of 77 20/06/11 10:10 AM

Page 38: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

One (whose name ends in ".c") provides the implementation view; it contains the complete declaration for the data type, along with thecode that implements its associated operations.The other (whose name ends in ".h" - header file) provides the abstract view; it contains short declarations for functions, pointer types, andglobally accessible data.

Previous Chapter | Next Chapter

Chapter 28Pointers notes

If you free a pointer, nothing happens to the memory there (ie. the region is not overwritten with zero), it memory allocator is just told thatsomeone else can now use that memory if they want to [that means that piece of memory will be overwritten later]The safest thing to do once a pointer has been freed is to set it to NULL which is a value guaranteed to point nowhere so that if you try to usea pointer you’ve freed you get an error.

NULL

NULL is a reserved word defined in stdlib.h that is a pointer that is guaranteed to point nowhere.There are a whole lot of other #defines in stdlib.h that you should probably check out at some stage.

Rest of the lecture

The rest of this lecture was spent talking about the logistics of the project, and ADTs which are covered in chapter 27

Previous Chapter | Next Chapter

Chapter 29Revision of typesint x

If we say : int x; we mean the variable called "x" is of type integer

just as if we say princess buttercup, we mean the person called buttercup is a princess.(note: there is a language called boo, where you can write x as int)

int * pointer

Similarly with pointers, if we say int * pointer we mean "pointer" is of type int *

Just like if we say sister of the princess piper, we mean piper is the sister of the princess.However, C reads int * pointer as *pointer is of type int.NB: int * p1, p2 DOES NOT mean p1 and p2 are pointer, only p1 is a pointer and p2 is an int,as C reads it: int (*p1), p2Also note: declaring 2 variables in a line, even if they are of the same type is AGAINST THE STYLE GUIDE!

New typesSteps to create new types:

1. DESIGN new type (interface functions)2. WRITE TESTS for new type3. IMPLEMENT new type

Example: Stacks

Designing a stack, functions needed:new: which creates a new stackpush: which adds an item to a stack and returns the new stackpop: which takes an item off the stack and returns the new stacktop: which returns the top item on the stackget max size: which returns the maximum size of the arrayget item number: which returns how many items are on the stack

Write interface (stack.h):

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

38 of 77 20/06/11 10:10 AM

Page 39: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 2 3 4 5 6 7 8 91011121314151617181920212223

/* * stack.h * ProjectUniSim * * Created by Richard Buckland on 2/05/11. * Copyright 2011 Licensed under Creative Commons SA-BY-NC 3.0. * */

#define STACK_SIZE 1000

typedef struct _stack { char items[STACK_SIZE]; int maxSize; int numItems;} stack;

stack newStack (void);stack push (stack s, char elt);char top (stack s);stack pop (stack s);int getMaxSize (stack s);int getNumItems (stack s);

Write tests for the stack (testStack.c)use the interface functions defined in stack.h to test stack.c

Implement the stack functions(stack.c)NB: testStack.c has a main whereas stack.c does not

Previous Chapter | Next Chapter

Chapter 30StacksRichard has now implemented newStack(), a function that returns an initialised stack, with no items, a maximum size of STACK_SIZE, and avariable (int) that holds how many items are currently in it.

The newStack() function:

Has a loop that sets items all to 0.Sets maxSize to STACK_SIZE.Sets numItems to 0.

Array in Function is OK

The fact that an array is created inside the function is not a problem when the stack is returned at the end (as normally you cannot return an arrayfrom a function). This is because when you return a struct, the entire contents of the struct (including arrays) is copied to the stack frame of thefunction caller.

When s is initially declared in main, an area of space is set aside. The stack returned fills this space, because they have the same type.

Interface Functions

In order to keep the data struct of this newStack abstract. We need to create communicating functions or interfaces. These functions return valuesand informations about the stack and allow user to modify their stack without knowing stack structure. Think of it as a bank teller. You don't knowhow bank manages your money but when you enquire teller about something(like how much balance you have in your account), they will returnwith the information you need.

For stack, we need interface functions such as:

POPPUSHTOPetc.(see previous chapter for full list)

We also need to be able to find out the current size and the maximum size of the stack.

You can make as many interface functions as you want. But for ADTs, don't just do stuff because you can. You could have a whole heap of features,but keeping it simple is a better approach.

KISS: Keep it Simple, Stupid.

Keep your interfaces as simple as possible. Don't ask 'will this be useful?'. Ask "Is this massively useful right now?", and if not, you probablydon't need it.

Functions that just get information from an abstract are called "getters". These are prefixed with get and are placed under the declarer. These keep

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

39 of 77 20/06/11 10:10 AM

Page 40: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

things abstract.

GENERAL PROGRAMMING ADVICEDo the easy stuff first. This is a good rule.Don't worry about doing stuff later on, do what you can do.Celebrate when you achieve your goals.

Abstract TestsYou should only test an abstract type using it's interface. This means if the interface doesn't say how the type is stored in memory, you cannot edit itdirectly. IE. Stack.maxSize would be editing the data structure directly, if Stack is meant to be used as an abstract type, you should not rely on howit is stored.

The purpose of this is that if the implementation ever changes, when you use the ADT your program and/or tests will still work.

For Teamwork 1.0, your tests can include accessing data directly, without using the interface, but later on, it is expected that you will only interactwith Game as an ADT.

Referenceshttps://openlearning.cse.unsw.edu.au/Comp1917/2011s1/stack.hhttps://openlearning.cse.unsw.edu.au/Comp1917/2011s1/stack.c

Previous Chapter | Next Chapter

Chapter 31Struct Abstraction

Struct Abstraction - No one else , apart from the struct creator, should violate the struct abstraction (i.e. directly refer to items inside thestruct by using . rather than ->). Note that the compiler couldn't catch this!

Also note that users should only communicate with the struct using interface (functions)

Pointer to struct - use typedef struct _game *Game{}; in the .h file, and declare all struct contents in the .c file instead. This createsabstraction (ADT).

Stack Application - Reverse Character[This stuff is from Lecture 32]

Printing character in reverse order exercise was used to illustrate

a) Stack usageb) Abstraction Data Type: Using Interface to communicate with the main function.

Previous Chapter | Next Chapter

Chapter 32Contents of Lecture 32 can be found in Lecture 31... This is due to the mass confusion about lecture number & video number

ADTs make it abstractADTs prevent you from seeing the inside, hence:ADTs prevent coupling. (physical representation can be different, e.g. USB & ComputersHeaders give pointer to a game you need:

Function to make a new gameShow the game is helpful but not necessaryPiece to make new gamesetting is helpful for debugging, but not actually make the game

MAKE IT STATICAfter we write tests!

time on war inversely proportional to importance

From Mon09Harp: thanks oliver, will be done asap :)

Previous Chapter | Next Chapter

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

40 of 77 20/06/11 10:10 AM

Page 41: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Chapter 33Summary

cuttlefisheslooking at averagesa little on portfoliosfinding HenryThe fish in the Mandelbrot server (unrelated: lets think of some names for the fish)debugging codethe psychology of debuggingships and logssoftware projects

Situations where you would look at averages and expected value

Weather, e.g. for planning a party on SaturdayWaiting for a bus or train. How long do you need to wait?

Richard used to live 15 minutes from the station. When did he leave the house? Of course, 15 minutes before the train leaves. Moreoften than not, Richard missed the train…Because he lived far away, he was often late to work and stayed overtime. Richard realised that during the week, on average, he waswaiting on average 50 minutes for the train. But if he turned up to the station randomly, he only waits an average of 30 minutes!So when a new train timetable came, Richard did not look at it.

This is a search problem.

The problem is we have a finite amount of time.

Randomness (randomly looking) is a reasonable first strategy. It could work.The unique things about humans is that if we think the strategy isn't working, we flip strategies.

Richard and his daughter divided the maze 4 quarters.When Richard couldn't find the wizard (somehow Henry the mouse became a wizard?), he said 'I can't find him, give me a hint'. His daughter would tell himwhat quadrant. Then Richard could find it. Psychologically, knowing he can find it helped him find it. He knew he could find it so he wasn’t givingup.

Being systematic is awesome but you don’t need to brute-force

What Richard likes about gridding is that it’s systematic. Being systematic is awesome.BUT it doesn't have to mean gridding. Gridding is a brute-force search. It's feasible on this smallmaze problem. It will always work. But it's slow.

What about finding the fish on the mandelbrot server - how can you find it? There are infinite tiles, so how can you divide it up and search throughthem all?

Bruteforce is a reasonable fall-back. But when your random strategy doesn’t work, you don’t need to drop to brute force. All you need to do is dropback to a systematic method.

Debugging codeWhen you're debugging your code, you look in the most likely place - look at the compile line/errors etc. You have the zoom problem too. You canlook on the problem on several levels - it could be syntax, memory etc. But you can't look 'infinitely hard'.

Richard: “ I think the art of debugging is the art of searching.”

What do you do when you don't find the bug after an hour of looking?

Go away. There is a psychological element to this. You don’t want to give up purposely or even accidentally (your brain has given up butyour eyes are still looking)Find a working instance and compare.Rewriting and doing it again. Richard comments that when you do this and the problem is solved, you can compare and find what theproblem was, so you can learn this for next time.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

41 of 77 20/06/11 10:10 AM

Page 42: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Debugging is a psychological thing. Infinite zoom applies so brute forcing would be difficult. Psychologically we need to know that it’s findable (orelse we would give up.).

Divide and conquer!

Quickly isolate areas where the problem isn’t. Printf-ing everywhere and see what’s wrong. Zooming in by adding more printfs in suspect areas,until you come to a few lines, or even one line. Debuggers aren’t necessary – all you need is the principle of isolating where the problem is –zooming into the right place. You can printf variables and find the problem. Richard’s ‘trick’ for debugging is to take a copy of the program and gocrazy with printfs.

Ships and logsCaptain Jack (was it Jack? would take a log and throw it overboard, tired to a rope with knots, take an hourglass and have the knots counted everyquarter hour (or other small interval). All of this was written on the ‘log’ board. And then the captain would copy all this stuff into his ‘log’ book.And then he could work out where they are.

This is what Richard does! He has a log-book. Apparently we, being the new generation, probably have a digital one (which is ok!). Richard writesthe results of all the tests and you can go back through the book and see what he worked on. This is a part of the whole systematic thing - keeping arecord of what's happening. Keep a history of the values.

So every step you make should be isolating the problem, not making conjectures and then guessing (although this can be done first).

Basically, log in the book the precise thing that caused the problem, e.g. for a particular combination of variables. Use the exact combination ofvariables. We need to be able to reproduce the error. Check whether you can reproduce it at other times. Write a test with those exact conditions init. Then you do the paring away - take stuff away and see what affects the error.

Zoom and divide, zoom and divide!

Back to software projects

Now back to software projects. There's a client. Say Macquarie bank. Then there's the software programmer. The two bosses talk.

Macq: Here's the things we want done.Software boss: ...Here, do it.

For a software project, you have these variables:[pretend these bullet points are knobs]

The scope (list of things you've got to do)Will increase!

ResourcesIncludes:

Stuff that’s not timeTime

Finite!Deadline

External constraintCode quality

This is interesting. It's quite stressful when someone asks you to write crap code...we're not happy. The rest of the world won't notice atfirst (though they will notice later when it's expensive when it breaks, you can't add xx feature etc)

What the agile guys noticed. You can't control three of them. But code quality is not negotiable. So we want it to be set on 'high' –always.

Theo's problem: hHe doesn't deviate from the code quality but things get massive and slow and late…tutors are getting annoyed.(Suggestion: get rid of the tutors)

You start working overtime, constantly stressed, and code quality is declining, and you won't be meeting the scope…

The brilliant thing. We only have enough time to do xxx. Theo works out which one he’s to do and which one he’s not to do. But thenthe tutors get annoyed! Why haven’t you implemented xxx, Theo?! Where’s xxx? xxx is broken!

That doesn’t quite work. So here’s another way to do it.

Here’s Theo’s to-do list.------------------

Can YOU add things to the list?

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

42 of 77 20/06/11 10:10 AM

Page 43: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

You might think that this doesn’t solve the problem. BUT IT DOES! We said that Theo’s going to work from top to bottom. YOU, as the client,know what’s important. When you add it to the list, YOU add it to the right spot. The CLIENT does the hard thinking about the priorities. Theofinishes what he finishes, starting from the top of the list. Everybody is happy. Hooray!

So for your AI:Add things one at a time. Rearrange your list whenever you like. Make an XP (explicit?) list. :D

Previous Chapter | Next Chapter

Chapter 34in the srsbiz world, no one cares about deadlines and everyone bends over for you when you miss them... NOT!

Richard was printing a business assignment. back then they had dumb terminals and everything looked ugly.

the lecturer put his assignment in a different pile. he mad it better, but he ended up with nothing. (all or nothing approach).

it's better to have incrementally better deliverables, so you can just hand in whatever you've got in the lecture.

he wasted loads of time on crap like bike sheds

Sayer's law says that the amount of effort that people put into debating something is inversely proportional to the importantness, so AVOIDIT. Don't mess around.

He's talking about a missile vs a cannon. a cannon is all or nothing. with a guided missile, you can change it's path along the wayless violent example. if he wanted to meet someone at town hall steps @ 6:02 and he doesn't say anything else, if they don't meet eachother, you're stuffed.these days we have mobile phones. all we have to say is "lol i'll meet you on saturday" and then use mobile phones to sort out later.

software eng: requirements group. talk to a company for a year working out requirementsfortress of solitude for years. then hopefully at the end you give the client exactly what they want

so you shouldn't do that cos you'll end up with nothing

in the 90s, most software engineering projects FAILED. very expensive software was never used

here's the new "mobile phone" way of doing it. you don't think the client is an idiot, but they might just not be great at software (that's whythey're rich). We want to respect them and get the client to become part of your team.

agree on all the jobs, then you post-it note it everywhere and you tell them "here are all the things we can do. you tell us what to do first."

the client is very clear what to do first and you do it. then when you give it to them they change their mind. it's better than them changing theirmind after you've done all the post-it notes

good question from Mark: pretty much a boss doesn't understand programming and what the right step is. so there's a need for infrastructurebut they put new tasks at HIGHER priority than the infrastructure than DEPENDS in the infrastructure.

richard's answer: bosses aren't programmers so they sometimes make crap decisions. they ALWAYS pick wizzbang new feature. eitherrestructure the database, take a lot of time and end up with exactly what you have now OR have COLOUR!!!

they don't understand that colour could cost less in the long term IF you did the boring thing first

if the boss tells you to do the wrong thing, you can't call him an idiot, but you can't. just be an idiot yourself and follow along with it.

it only arises because you haven't communicated with the boss properly and given him enough information

we're being too abstract, and bosses only see concrete stuff

it's annoying when you try to persuade someone of something and they don't agree but they're not an idiot

one approach when dealing with business people is to talk about investment in software infrastructure (making code clean) by using theOPPOSITE as an example. He'd say that "we're in design debt". Everyone understands debt. Our design is behind. We now have to paydesign costs (interest). Things take longer to write, the system breaks more often, takes longer to add new features. Every month we take 10hours fixing crap up just because it's crap. He might still decide the other way if he can afford it, then fine!

a load of old software was written in COBAL. it was great, but you wouldn't want to write something in it now. they've gotta weigh up thecosts of switching or not.

knowing COBAL is like a licence to print money. richard's friends fly around in jets all day

richard's talking about risk for the 9001st time. we're shit at making sensible decisions. risk is a trendy word, and all these MBA people.

if systems are old, you could end up with your butt getting raped like sony with low probability but gignormous impact

everytime the NAB goes down, richard sits there giggling. it's happened like 20 times this year.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

43 of 77 20/06/11 10:10 AM

Page 44: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

if stuff goes wrong you lose that intangible customer trust

Previous Chapter | Next Chapter

Chapter 35

Static functions should exist only in the functions that use them. i.e. don't declare in header file.

Too late is just no good. Don't try an all of nothing approach.

Richard talks about the colour of bikesheds too much. "The amount of time spent on an argument is inversely proportional to its significance."

Programming Structure:

Old way: Client info (list) -> Fortress of solitudeNew way: Client info (constant feedback) -> Client is boss (makes decisions)

If the boss is wrong and not an idiot, you are.

Students forced to watch EuroVision.

Skype bought by Microsoft.NET -> Sky.NET

AI - Mr. Dumbo - easy 1 mark. (he stole my strategy)

- AI = 2 marks- Correctness = 1 mark

Richard's runGame.c makes 4 copies of the game and gives each AI a copy.

AI is called and given a copy of the game as a parameter and returns an action.

Feel like there's a whole chunk of info he talked about that isn't written here...

About the 3D satellite imagery for natural disaster management using data received by electrical engineers then processed by computer science andtagged by environmental management:

http://xkcd.com/755/

Previous Chapter | Next Chapter

Chapter 36Hu-Array! - What is so good about itRichard asked the class why are arrays good? some replies were

multiple stuff can be storedthey can be indexed

Other good stuff about arrays is that

fast to get a elementrandom addressing

negatives of arrays

Don't know where to stop, need to be kept track of all of valuesCan't easily insert valuesFixed size

Linked listcode by Luke Cameron

List.c

the actual code is deleted to decrease the difficulty of the exam.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

44 of 77 20/06/11 10:10 AM

Page 45: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Linked List - Be Careful!

Remember to make list a typedeffed pointer to a list "List".

newListmalloc a listinitiallize the values of the listCare about the address of the pointer pointing to, they should be NULL

appendItemScan through the list using while loopStop when you get to the right position(ie when the "next" pointer is NULL)

note:care about the special case when the list have no items, it's different when you have items in the list beforehand since you need to change thepointer "first" to point to that item.

getItemthe same procedure as your appendItem but the only difference is you need to get the content of that node rather than appending items to it.

Alternate Explanation is available at the Revision Section

List.h

1 2 3 4 5 6 7 8 91011121314151617

/* * List.h * lecture-code * * Created by Richard Buckland on 16/05/11. * Copyright 2011 Licensed under Creative Commons SA-BY-NC 3.0. * */

typedef char item;typedef struct _list *List;

List newList (void);void showList (List l);int length (List l);item getItem (List l, int position);void appendItem (List l, item i);

testList.c

1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445

/* * testList.c * lecture-code * * Created by Richard Buckland on 16/05/11. * Copyright 2011 Licensed under Creative Commons SA-BY-NC 3.0. * Modified by Luke Cameron on 16/06/11. */

#include <stdio.h>#include <stdlib.h>#include <assert.h>#include "List.h"

int main (int argc, char *argv[]) { printf ("testing newList\n"); List l = newList (); assert (l != NULL); printf ("testing an empty list has size 0\n"); assert (length (l) == 0); appendItem (l, 86); assert (l!= NULL); assert (length (l) == 1); appendItem (l, 99); assert (l!= NULL); assert (length (l) == 2); printf("testing getItem\n"); // remember that this getItem assert (getItem(l, 0) == 99); // inserts items at the start assert (getItem(l, 1) == 86); printf("testing showList. " "If this doesn't look right, then disregard " "the following \"you are awesome\" statement.\n" ); showList(l); printf ("All List tests passed! You are Awesome!\n"); return EXIT_SUCCESS;}

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

45 of 77 20/06/11 10:10 AM

Page 46: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

GENERAL NOTES--Damon Griffiths (Damon Stacey)

This week richarded started the lecture by showing a snipt of video which richard claims should have won the eurovision contest. Richard then toldus about a book Wuthering Heights by Emily Bronte. One girl in the class said that "Heathcliff was a dick" as i wasn't familiar with the book i was abit confused to as to what was happening.

Richard referred to eurovision theme, saying how france make good things every year and lose, because they know they are too good and neverwin, but never make crappy stuff so they can win, while the United kingdom does the exact same thing to lose.

Previous Chapter | Next Chapter

Chapter 37Oliver Engelmann here from Joel's tute. Sorry, didn't realise we were taking notes on this day. I'll watch the lecture videos and hopefully havesomething up tonight (25/05/2011)

Previous Chapter | Next Chapter

Chapter 38Computer Memory

Big Endian - most significant byte is stored at lowest end of memoryMost significant digit/byte is the one at the leftmost of the number(in number 365, 3 is the more significant than 5)e.g. 1 (decimal) : 00000001 (Big Endian binary)

Little Endian - least significant byte is stored at lowest end of memoryLeast significant digit/byte is the one at the rightmost of the number(in number 365, 5 is the less significant than 3)e.g. 1 (decimal) : 10000000 (Little Endian binary)BMP binaries are stored in this manner.

To test whether the computer memory has big endian or little endian memory:

1 2 3 4 5 6 7 8 9101112131415161718

int x = 1;char c = (char) x; //(char) - casting //print char would give contents of x

int *p;p = &x;

char *charPointer;charPointer = (char*)p;

printf ("%p", p);printf ("%p", charPointer);

if (*charPointer == 0) { printf ("it's 0\n");} else if (*charPointer == 1) { printf ("it's 1\n");}

Stack Frame

local variablespointer-> return address

parameters

R1 load reltive |10|segment register |100|-> output = 110

For example:

Time

5 o'clock in the afternoonload 11 hours -> 4 o'clocknegatives values are allowed in modulo

Limitations

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

46 of 77 20/06/11 10:10 AM

Page 47: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

different segments cannot overlapcertain segments are marked to do certain actions onlysegmentation fault - illegal action (able to accessing information which we shouldn't be accessing - ie. read only)usually caused by arrays, pointers and string copies

Debugging

find and solve segmentation faults by using printfs and assertsuse debugger:

mudflapvalgrindgdb - leave out capital "O" (alphabet), put in a "g"\

Extra Exercises

Do 3D blue mountain picture exercise from the lab when there is time, even if it's in the holidays.

Amazing and fun!!!

Introduction of 8006 microprocessor

Richard now wants our help building the 8006. He found that people asked for two main thigs; fixes to the annoying problems of the 8004, andextra things that aren’t needed.

Changes:

255 not big enough; however, instead of increasing the byte size, have 4 registers, so can load 16 bit numbers (half in each). But then we needa way to print 16 bit numbers.it is a pain to deal with framesThe stack is a pain

Instead of 2 registers, has 4. Allows for 16bit arithmetic, by storing one number in two registers.

1 byte is 8 bits

Convention that we talk about memory in chunks of 8 bits, ie bytes

Byte order: which way to store an int, most significant figure on the little end or big end? doesn't matter, as long as everyone complies with thestandard. Generally it's done with most significant byte on the right.

Project discussionsDiscussion of paths in the project. The two sides of the debate: paths that go off the board, but come back are allowed (for the affirmative)and (for the negative) paths are not allowed to cross off the board at any stage. The final consensus seemed to be that you are not allowed togo off the board with your path, regardless of whether or not it ends up back on the board.We shouldn't need to check for illegal input into functions because it is not in the spec and it is beyond the real of this course.Richard mentions the "Modelling Approach" which will apparently make our toes curl and also layout a definitive result for the path debate(from above).Lights analogy: People who own the theatre (to be built) don’t specify the details of the lights, because they think no one will ever use them.The builders/designers of the hall choose to put deadly laser beams in the lights and somebody uses the lights… This is analogous to whetherthe spec ambiguity matters or not. If the details are not specified, some people’s games will break because of different interpretations of thespec (details need to be specified).

The spec had ambiguity in how a player is allowed to move across the board. It was unclear if a player was allowed to reach the final destinationthrough a path which went off the board. This raises interesting questions about the spec and how it is interpreted. In a sense, going off the boardwhen executing a path is an illegal move within the legalities of the physics of the game. Richard has made it clear we are only required to checkthe things well formed in the spec. This means that while we are entitled to check the legality of each move of the path, we only are required tocheck the final destination. The final decision was that a player must stay on the board at all times. In this case, the game engine does not have to bechanged; the ai’s do. This is considered to be the easier option. This problem represents the heart of abstraction. In a concrete sense, it does notmake sense to be able to go off the board at all. However, in an abstract sense, as long as the final destination is on the board, it is fine. Inabstraction, we may not realise certain errors that make turn into a killer problem we won't now of. Richard’s metaphor comes to the position oflights in the lecture theatre. If we don’t specify we want white light, the builders may install lasers instead. While this will affect lecturers whoconstantly use those lights, to the ones who don’t there will be no difference. It is thus imperative that a common interface is agreed upon, wherethere is no ambiguity. The question, however, now turns to how general or specific code should be. With reference to the board, a general codeseems much better; should the size need to be changed, only a bit of code will need to be changed. This was the thinking of Richard in 1980’s. Inthe 2000’s, we have tests for our code. Therefore, should we change our code, we have tests to fix them up. Therefore, the specific code is better.This follows the agile philosophy of extreme programmers; to be courageous, make the massive changes in code so it works, then go about makingit look nice (refactoring). For the first time, make something concrete. Should it be repeated, consider making it general. Should it be repeatedagain, make it general. Follow DRY; don’t repeat yourself. If you see code that’s repeated, refactor it.

Previous Chapter | Next Chapter

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

47 of 77 20/06/11 10:10 AM

Page 48: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Extension Lecture

Chapter 39

Previous Chapter | Next Chapter

Chapter 40

NSBHS Lecture Notes - Lecture 40Week 10, Lecture 1

TestsUnless you have really thorough tests, it’s quite possible you will accept a game that still has a flaw in it. It’s in your interests to test that somethingis wrong, so make your tests really good, otherwise you might get a dodgy game.

Out in the real world, you can’t give your boss some code and then at the end say “Can we use the correct code? Can we just use the code I gaveyou for testing and my performance bonus?”

There is no ‘correct code’ in the real world.

Parts of ‘correct code’

A good testing planA good design approachGood stylePeer review But, they’re not the whole thing!

CheatingYou could free the game! But then the game would segfault.

Two ways to cheat:

Rig the dice so that you get to choose students.This will only help if you get your own game.

Don’t start being malicious until a large number of turns.Defend yourself by testing long games.

If Richard owns a factory next to a beautiful river that pollutes, it hurts Richard a little bit to pollute and stink the river but it makes Richard a bigprofit i.e. The cost is distributed among heaps of people, but only Richard profits.

If you write slightly crappy game, everyone will get lower scores but you might never get the game yourself. Then you are pulling everyone downexcept for you.

If you try to cheat, most of the time you will crash. You could try a very complicated path, but it may impact on your quality of game. Think abouthow you can break, then think about how you can protect it.

Rule of the game: NO CHEATING. If you are cheating, and you are caught, then you will be excluded. Beginning of the course; think of all therules of a game that no one stated, but are still rules.

How do you detect cheating?

Hit someone with a log if they cheat?Continue this discussion on the forum.

Famous attack - Italian Attack

It caused them to stop having preferential voting, so they went back to crappy election system They did this clever cheating attack that identifiedpeople. Australia is open to this attack right now.

How does it work?

The mafia says 'Vote for Berlusconi (the really rich guy) or we'll break your knee caps'and you say 'Sure' (but you go in and vote and it's secretwhen you vote, so you laugh and vote for someone else). But it only works if later on they can't work out who you voted for. Just like this cheatingconcept.

Australia's voting is preferential voting (vote by giving a list of all your preferences),NSW has like more than 50 canididates And you have to give rankings for all of them, so how many different ways is this possible?

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

48 of 77 20/06/11 10:10 AM

Page 49: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

50 factorial. Gobsmackingly big.How many people in the NSW electorate?Much Much Much less than 50 factorial.The chance of a random vote occurring randomly is essentially 0.So how you vote is vote for one person, then they give you 2-50 and say vote for that. *Then they can check to see who did vote and whodidn't. The chance of someone else *casting that vote is 0.In Australia it is facilitated because we release electronically every single vote counted on a CD (from the ABC)(And Richard likes looking at his vote checking it's still there)

That's known as the Italian Attack.

ListsRichard is worried about everything being so busy busy busy, and people aren't doing the lab exercises because their just working on their projectsand everything's busy.

He's nervous that some people may be thinking 'I just won't worry about this, I'll worry about it later on'

But he encourages,

PAY ATTENTION

DO THE LAB EXERCISES

DO NOT PROCASTINATE TO UNDERSTAND

lists- nodes, and the final one has a cross in it

Example numbers; LIST -> 99 -> 86 -> 13|X

How do you delete? Draw pictures!!!

Set up another pointer somewhere pointing at 99 (the 'before' guy)1.We need a pointer to the guy that we are going to delete as well (the 'guy') (think of as strings and balloons, if it's not tied to them, it will blowaway)

2.

Then;

before->next = before->next->next;Free node 1 (but then there's a pointer (guy)make guy NULL (to make sure no one uses that pointer. E.g. the movie with one nuclear destruct button and one expresso button and theiridentical next to each other and don't know which to push)

When would you create the pointers?

In a loop;Scanning to find the position, and the one before it.

How does 'free' work?

free (pointer);

Why is a function for disposeGame needed?

The game is abstractGame is a huge struct with a pointer pointing to itIf it is freed, the entire struct is freedIt would be fine if all the information was in the struct, but what if there was a pointer inside that struct pointer to information outside of it?Only the Game struct would be freed, the other information would be floating around.Only the creator knows what memory the game consists of and if and where the outside information is.This is fixed through freeing the outside information (outside the struct etc.)

BugsBugs similar to weeds, sometimes the approach to removing the bugs in programs can make it worse.

What makes a good bug?

Subtlety (hard to detect)Small effect

Occurs rarelyMasks behaviour and locationEmotional connection

Don’t want to remove itNot triggered in testingMakes the program worse when the bug is removed

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

49 of 77 20/06/11 10:10 AM

Page 50: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

You has homework! Think of other features/characteristics of the best bug. NO SPECIFIC EXAMPLES. What is it? Why is it good?

Machine Code Frames - 8004

% store R1 temporarily, then refresh it

STUFF % when we have out answer, we need to make the last addresses go back to original address

% Dump R0 somewhere

% now get return address and restore it

% store in jump location

% now get back the return value to R0

% retrieve R1

% Go back to position, 0's are rewritten!

a = return to address

b = input number

c = r1 location temp

d = dump location

e&f = return locations

Previous Chapter | Next Chapter

Chapter 41Freeing the game through your ai is a bad idea as it is abstract and you do not know if it points to other malloced parts of memory.

List StuffLinked list are important so do the work on them and understand them.

Deleting nodes

List: x is a pointer to the next nodeBefore is a pointer to the node before the one to be deleted

Guy is a pointer to the one to be deleted

Before Guy

| |

| |

__________ | |

| List | _V__ __V_ ____ ____

| | | 0 | | 1 | | 2 | | 3 |

| x | -->|data| -->|data| -->|data| -->|data| -->NULL

|__________| |__x_| |__x_| |__x_| |NULL|

Void function deleteNode(List l, int position);

deleteNode(l , 1);

STEPS

Create a pointer to the node at position -1 (Before)Create a pointer to the node at position (Guy)Copy the pointer of node 1 into the pointer of node 0. Before->next = Before -> next -> nextFree the node pointed to by Guy and set Guy to null.Deleting the first node is a slightly different process as it is pointed to by list.

COMPETITIONPractice round every night before the competition runs to see if your ai can run properly.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

50 of 77 20/06/11 10:10 AM

Page 51: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Making last changes to your ai for the competition round is a bad idea.

Some game mistakes don’t manifest themselves unless the conditions are right. Make tests the best possible to catch all bugs.So write code withgood style and review the code because in the real world your code is the ‘right’ code.

Methods for cheating

Rig the dice so only you receive students, or set the game up to run correctly for a while then start doing weird things.

Potential ways to check that your player is playing your game: Sign your identity by sending a specific code/identifier.

Methods to check for cheating

Test long games.

However to cheating is against the rules, and if you get caught you will be excluded.

Italian attack, voters identifiable by the sequence of the numbering on their voting paper. Voting was preferential, in Italy.For n preferences there aren! possible ways of voting. The mafia assigned people a specific preference list and then checked that specific preference list was fulfilled, if not theperson was against the mafia. Due to the high number of possible combinations and low in comparison population the chance of a certain voteoccurring is low.

BugsBush regeneration, and weeds.

Guys method for destroying weeds

Destroy everything, e.g. bulldozers, flamethrowers.

However this only made things worse, so a study began on how weeds work and how to destroy them.

Weeds are very similar to bugs in our code and sometimes the methods we use to destroy bugs is making things worse.

What makes a good bug

Self replication

Subtle: Occurs rarely, Masks its behaviour

Removing the bug can cause more problems.

Gets exponentially worse.

Achieves a big thing by doing one small thing at a time.

Triggered by external factors that do not occur on your computer.

Previous Chapter | Next Chapter

Chapter 42It's important to think about tough decisions before you run out of time. Regardless of the choice you make, the important thing is that you'vethought it out in advance to reduce the chance that you'll regret it and feel shit for the rest of your life.

Previous Chapter | Next Chapter

Chapter 43Empty.

Previous Chapter | Next Chapter

Chapter 44The lecture started off with richard getting shot by a nerf gun.(actually this was lecture 46 according to the videos)

Previous Chapter | Next Chapter

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

51 of 77 20/06/11 10:10 AM

Page 52: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

CHAPTER 45In which Richard gets his oats

I'm writing this after you've finished your first year Math exam. Well done! Studying for this exam was discussed, the Project was discussed,Battenberg Cake was discussed.

If you're reading this in the exam, pat yourself on the back for doing the Project! If you aren't in the exam, pat yourself on the back for doing theProject!

Next time you see Theo, pat him on the back!

Reflection is good! Ah wait I don't need to write this chapter, it's not going to be in the exam!

Music!

Remember, as things get more and more complex, your program can have exponentially more errors. If your code in the answer to the examquestions is getting very convoluted, maybe take a step back and re-evaluate your approach to the problem.

If your code is incorrect, you should get zero.

You won't find any of the answers you need for the exam here. Sorry.

Previous Chapter | Next Chapter

CHAPTER 46

The Revision BeginsSome taken from previous years textbooks (Mainly 2008), and otherwise my memory used for revision and occassionally a google to remember theexact stuff! :D Referenced where needed! :D

I Started trying to make my notes on all this fit into the rest of the testbook but thought this was a better way as a quick reference section foreverything u need to know.

Think of this as a formula booklet with explanations! :D

Index:

C Syntax argv, argc, heap, stackGeneral Stuff<stdio.h<stdlib.h<assert.h><math.h><string.h>

Microprocessors Our standard stuff4003400480048006 (not realy here.. its an imaginary processor given under exam conditions

Example Code Something SimpleishBMP writingSomething playing with arraysSomething playing with stringsSomething playing with bitwise operatorsLinked List Example (By Mathew Moss)A server output AND File IO

Tables Ascii->Hex->DecimalDecimal->Hex-> Binaryvariable types and Thier size and escape charsEscape Characters in CBinary To Hex To Octal To Decimal table (SHORTER)

C Syntax

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

52 of 77 20/06/11 10:10 AM

Page 53: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

ARGV vs ARGC

in the declaration of main in c (int main (int argc, char *argv[])) argc is the count of arguments passed into the function, and argv is an array ofstrings which are the arguments passed into the function.

When gcc is run to compile testGame.c with -Wall -Werror to a file testGame i.e. command ot run compiler is gcc -Werror -Wall -O -o testGametestGame.c

argc in this case (of gcc) is 6.

argv[0] = gcc

argv[1] = -Werror

argv[2] = -Wall

argv[3] = -O

argv[4] = -o testGame

argv[5] = testGame.c

when running testGame with command

./testGame

argc is 1.

argv[0] = ./testGame

Heap vs Stack

Stack records data from bottom up.

Heap records data from top down.

Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.

Stack stores data in order (from bottom up): Parameters and datatypes, return address, Registers, then local variables

The heap is more for dynamic memory allocation. Runtime thing.

The heap uses a LIFO setup (last in first out)

Malloc sets aside memory on the heap.

All other local variables are on the stack. Its more things from compile time.

Comments

Comments are text in the code that the complier ignores. An example is shown below. The does not need to be at the start of the line, you may addit after some code. It just means that everything after the on that line will be ignored by the compiler.

1 / / this text is ignored by the complier

if

if statements look like this.

123

1 if (expression-to-test) { 2 statements-to-execute; 3 }

in this example the statements will only get executed if the expression is found true (ie, you could test for something like a variable equalling acertain number), otherwise they are skipped. The other way of using if is to include an else.

12345

if (expression-to-test) { statements-to-execute; } else { statements-to-execute; }

in this example if the first expression is true all the statements inside it are executed (and then the statements in the else bracket are skipped),otherwise if found false the statements inside it are skipped and the program executes the statements inside theelse's brackets. You can also testmultiple expressions as follows:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

53 of 77 20/06/11 10:10 AM

Page 54: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1234567

if (expression-to-test) [ statements-to-execute; } else if (expression-to-test) { statements-to-execute; } else { statements-to-execute; }

while

while statements look like this:

1234

while(somethingIsTrue) { execute this code; updateWhetherSomethingIsStillTrue;}

This is the easiest way to perform recursion. The code to be executed can be repeated many times with data thats updated each time its run!Alternatively it can simply be repeated a set number of times. Printing something so many times can be accomplished as simply as:

1 2 3 4 5 6 7 8 910

//initialising a counterint counter = 0;while (counter < 10) { //printing something printf("Something\n"); //updating the counter so that it will eventually stop //printing after 10 times (i.e. while conditions are //eventually not met. counter++; }

#include

The syntax for #include is,

1 #include <file.h>

What this basically does is it tells the complier to include the code found in the file.h; the compiler will then treat the contents of the indicated file asif they were already part of your program. These files are know as header files. Details for all header files are below

typedef

Typedef creates an alias of a type. You use it when you want to employ an existing type for a more specific purpose. The syntax is:typedefExistingType NewName; An example:

1 1 typedef unsigned char byte;

struct

structs are collections of different types of data that can be used together. For example you could have a struct of 3 ints recording how much of RedGreen and Blue you are storing for a pixel. Or you could store somebody's username (string), password(string), ID Number (int), Favourite Number(long float) etc.

Example:

123456

struct _user { char username[LENGTH_OF_USERNAME]; char password[LENGTH_OF_USERNAME]; int IDNumber; long float favNumber;};

To call data from a struct you do the following.

!#C

struct _user myNewUser = getUserData;

printf("the users password is: %s", myNewUser.password);

//...

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

54 of 77 20/06/11 10:10 AM

Page 55: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

struct _user getUserData {

struct _user userData;

//....

return userData;

}

BitWise Operators

We didn't really cover these.. but are interesting. Leaving this here, somebody can fill in the details if they want. If You've done discreet math thesesimply apply as in truth tables! :D

NOT ~AND &OR |

XOR ^

also note:

Shift-Left <<Shift-Right >>

<stdio.h>

This allows for Input/Output functions such as printf() and scanf() to be used. stdio.h stands for STandarD Input and Output.

printf

The printf() function allows text to be displayed on the screen. An example,

1 printf ("I have 3 chickens\n");

This will display in the terminal (on the screen)

1 I have 3 chickens

The \n symbolises the carriage return character (i.e. it is a new line). However if we wanted to have a variable displayed in "3" we would need to dosomething like,

1 printf ("I have %d chickens\n", 3);

We could also extend this to display a variable,

12 int numOfChickens = 3; printf ("I have %d chickens\n", numOfChickens);

scanf

The scanf() function is the inverse of printf(); it reads input that the user types on screen. For example,

12 int numOfChickens; scanf ("%d", &numOfChickens);

This will wait for the user to type in a value and assign it to numOfChickens. Note that as numOfChickens is an integer, entering a non-integervalue will result in that value being converted to an integer (characters for example will result in their ascii partners)

getchar

Tip: use getchar() like this:

1 2 3 4 5 6

// a program snippet to read in a string of charaters // and print out all the **b**sint input;input = getchar();

while(input != EOF) {

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

55 of 77 20/06/11 10:10 AM

Page 56: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

7 8 91011

if (input == 'b') { printf("%c",input); } input = getchar();}

putchar

from wikipedia: Use putchar as follows to print input received from the keyboard back to the screen one char at a time:

1 2 3 4 5 6 7 8 91011121314151617

#include <stdio.h> int main(void) { char str[1000]; int ch, i, n = 0; while ((ch = getchar()) != EOF && n < 1000) str[n++] = ch; for (i = 0; i < n; ++i) putchar(str[i]); putchar('\n'); /* trailing '\n' needed in Standard C */ return 0; }

sscanf

(i.e. string scanf) Its first argument is a string with information, the second is a format, the third is the variables to scan data in (same as for scanf)quotes from the server below:

123456789

requestData pullData (char request[0]) { requestData theRequest; sscanf(request, "GET /%c-%lf-%lf-%d", &theRequest.type, &theRequest.x, &theRequest.y, &theRequest.zoom); return theRequest;}

sprintf

(i.e. string printf this does the opposite to sscanf.. given x and y as below, it will set the string filename (e.g. x= 1, y = 2) to3DViewer/1,2Texture.bmp

123

char format[] = "3DViewer/%d,%dTexture.bmp"; char filename[sizeof format+100]; sprintf(filename, format, x, y);

fopen/freopen/fclose

Not covered really in course, but its here.. :D when dealing with files we first must initialise a variable of type FILE. note use of FILE type. we mustthen open the files and close them in the end.

e.g. from server below opens and closes a file 3DViewer/1,2Texture.bmp:

123456

FILE *inputTexture; char filename[25] = "3DViewer/1,2Texture.bmp\0"; inputTexture = fopen(filename,"r"); fclose(inputTexture);

when reading in filenames from a users input ensure filename is not an array larger than FILENAME_MAX, Also that you dont open more thanFOPEN_MAX files.

you can use tmpfile to store things temporarily

The following things step through a file sequentially and either get the current character or puts a character there:

fgetcfputc

for example:

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

56 of 77 20/06/11 10:10 AM

Page 57: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

12345678

int i = 0; int temp = 0; int 55thNum; while (i<54) { temp = fgetc (listOfNumbers); i++; } 55thNum = fgetc (listOfNumbers);

steps through the first 54 bytes and does nothing with them, but then assigns the 55th number to the variable 55thNum. Problem, u cant go back..unless u close and open the file without the function below i havent explained.

similarly:

12345678

int i = 0; int arrayOfNums[] = {i, i++, i++, i++, i++, i++, i++, i++, i++, i++}; i=0; while (i<9) { temp = fputc (0); i++; } fputc(arrayOfNums[i];

will print 9 0's to a file then print the 10th value in the arrayOfNums to the file.

The following just are too complex for them to likely ask us to use these.. so they are here but not explained: fgetpos... fseek.. fflush (writesbuffered stuff to output.. write ur own assert thing thats better?)

FOPEN_MAX && FILENAME_MAX

Interesting: stdin is of type FILE as is stdout, and stderr. you could so some funny things here.. :D

perror

reports error back to stderror from wikipedia:

12345

int fd = open("/etc/passwd", O_RDONLY);if (fd == -1) { perror("open"); exit(1); }

would print open: Access Denied

<stdlib.h>

rand

outputs a pseudo random number... you must seed it to make it more random.

its as easy as (to generate a number between 1 and 6)

123

//from damons AIrater srand(time(NULL)); int diceScore = rand() / ( RAND_MAX / 6 + 1 );

malloc

calling malloc sets aside memory on the heap for something. It returns a pointer to the first byte in the memory set aside.

e.g.

1 int *pointerToMemorySetAside = malloc(sizeof(dataToBeStored));

free

calling free frees this memory that was set aside, meaning that memory isnt permanently set aside. e.g.

1 free(pointerToMemorySetAside);

system (calls)

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

57 of 77 20/06/11 10:10 AM

Page 58: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

It is really the way of typing into a terminal from inside a program.

12 system("pwd"); system("ls");

exit

terminates the program we didnt cover this, forbidden by style guide, lets skip it.. :D

atexit

allows you to call a function if/when the program encounters exit. we didnt cover this, forbidden by style guide, lets skip it.. :D

abort

terminates the program with error (abnormal termination) we didnt cover this, forbidden by style guide, lets skip it.. :D

bsearch

(binary search of an array... ;D) we didnt cover this, lets skip it.. :D

MATH-

abs(int)

returns an int which is the absolute value of the input.

is type conversions in stdlib? not sure... will need to look up and update here / / / / / / / / / also note things like div and ldiv.. but we havent touchedthem and are easily written.

<assert.h>

Including this library allows you to run the function assert.

Its use is simply to debug whether or not something is true.

Example: The following will do nothing.

12 int a = THE_MEANING_OF_LIFE; assert(a == THE_MEANING_OF_LIFE);

However if the following is run, then the program will end when it reaches this point with an error code saying assertion failed.

then all asserts will be ignored. Helpful when you dont want your program just dying and want to hide any mistakes youve made from a user.. D:Not good form, but something to consider..

<math.h>

From Wikipedia for all c99 or later: note: size_t is generally an unsigned int... but varies between processors/operating systems

Name Descriptionacosh inverse hyperbolic cosineasinh inverse hyperbolic sineatanh inverse hyperbolic tangentcbrt cube rootcopysign(x,y) returns the value of x with the sign of yerf error functionerfc complementary error functionexp2(x) raise 2 to the power of x, 2xexpm1(x) one less than the exponential of x, ex − 1fdim(x,y) positive difference between x and y, fmax(x−y, 0)fma(x,y,z) multiply and add, (x * y) + zfmax(x,y) largest value of x and yfmin(x,y) smallest value of x and yhypot(x,y) hypotenuse, sqrt(x2 + y2)ilogb the exponent of a floating-point value, converted to an intlgamma natural log of the absolute value of the gamma functionllrint round to integer (returns long long) using current rounding modelrint round to integer (returns long) using current rounding mode

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

58 of 77 20/06/11 10:10 AM

Page 59: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

llround round to integer (returns long long)lround round to integer (returns long)log1p(x) natural logarithm of 1 + xlog2 base-2 logarithmlogb extract exponent from floating-point numbernan(s) returns NaN, possibly using string argumentnearbyint round floating-point number to nearest integernextafter(x,y) returns next representable value after x (towards y)nexttoward(x,y) same as nextafter, except y is always a long doubleremainder(x,y) calculates remainder, as required by IEC 60559remquo(x,y,p) same as remainder, but store quotient (as int) at target of pointer print round to integer (returns double) using current rounding moderound round to integer (returns double), rounding halfway cases away from zeroscalbln(x,n) x * FLT_RADIXn (n is long)scalbn(x,n) x * FLT_RADIXn (n is int)tgamma gamma functiontrunc truncate floating-point number

<string.h>

NULL is included in this, a pointer to unused memory.'

from wikipedia: (sorry im lazy, and this gives u better information...)

Name Notesvoid *memcpy(void *dest, const void *src,size_t n); copies n bytes between two memory areas; if there is overlap, the behavior is undefine

void *memmove(void *dest, const void*src, size_t n); copies n bytes between two memory areas; unlike with memcpy the areas may overlap

void *memchr(const void *s, int c, size_tn); returns a pointer to the first occurrence of c in the first n bytes of s, or NULL if not foun

int memcmp(const void *s1, const void *s2,size_t n); compares the first n bytes of two memory areas

void *memset(void *, int c, size_t n); overwrites a memory area with n copies of cchar *strcat(char *dest, const char *src); appends the string src to destchar *strncat(char *dest, const char *src,size_t n); appends at most n bytes of the string src to dest

char *strchr(const char *, int c); locates character c in a string, searching from the beginningchar *strrchr(const char *, int c); locates character c in a string, searching from the endint strcmp(const char *, const char *); compares two strings lexicographicallint strncmp(const char *, const char *,size_t n); compares up to the first n bytes of two strings lexicographically

int strcoll(const char *, const char *); compares two strings using the current locale's collating orderchar *strcpy(char *dest, const char *src); copies a string from one location to anotherchar *strncpy(char *dest, const char *src,size_t n); write exactly n bytes to dest, copying from src or add 0's

char *strerror(int); returns the string representation of an error number e.g. errno (not thread-safe)size_t strlen(const char *); finds the length of a C stringsize_t strspn(const char *, const char*accept); determines the length of the maximal initial substring consisting entirely of characters in accept

size_t strcspn(const char *, const char*reject); determines the length of the maximal initial substring consisting entirely of characters not in rejec

char *strpbrk(const char *, const char*accept); finds the first occurrence of any character in accept

char *strstr(const char *haystack, constchar *needle); finds the first occurrence of the string "needle" in the longer string "haystack"

char *strtok(char *, const char * delim); parses a string into a sequence of tokens; non-thread safe in the spec, non-reentrantsize_t strxfrm(char *dest, const char *src,size_t n);

transforms src into a collating form, such that the numerical sort order of the transformed string isequivalent to the collating order of src

WHATEVER ELSE WE CAN USE?

Microprocessors

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

59 of 77 20/06/11 10:10 AM

Page 60: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Standard Procedures with our microprocessors

Frames

Return value from a function is returned from R0

R1 is returned to its pervious state from a function when completed

First byte of all frames are the return address of the function

Subsequent bytes are input values

These are not to be changed by the function unless ABSOLUTELY necessary..

General

When moving between functions, registers are returned to the state same as when a function left the previous one (e.g. movement between main and

The 4003

16 memory cellsSystem Registers: IP, ISTwo general registers: R0, R1

0 Halt1 R0 = R0+12 R0 = R0-13 R1 = R1+14 R1 = R1-15 Swap R0 <-> R16 Beep7 Print R08 Jump to <address> if R0 != 09 Jump to <address> if R0 == 0

The 4004

Registers: IP, ISTwo general registers: R0, R1

0 Halt1 R0 = R0+12 R0 = R0-13 R1 = R1+14 R1 = R1-15 R0=R0+R16 R0=R0-R17 Print R08 Jump to <address> if R0 != 09 Jump to <address> if R0 == 010 <value> -> R011 <value> -> R112 R0 -> <address>13 R1 -> <address>14 R0 <-> <address>15 R1 <-> <address>

The 8004

Registers: IP, ISTwo general registers: R0, R1

0 Halt1 R0 = R0+12 R0 = R0-13 R1 = R1+14 R1 = R1-15 R0=R0+R1

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

60 of 77 20/06/11 10:10 AM

Page 61: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

6 R0=R0-R17 Print R0 as an unsigned int

first cell contains the instruction, second is called the data cell

8 Jump to <address> if R0 !=0 data cell contains the address to jump to

9 Jump to <address> if R0 ==0 data cell contains the address to jump to

10 <value> -> R0 load the value stored in the data cell into R011 <value> -> R1 load the value stored in the data cell into R012 R0 -> <address> write the contents of R0 into a memory cell. The memory cell used is the one pointed to by the data cell13 R1 -> <address> write the contents of R1 into a memory cell. The memory cell used is the one pointed to by the data cell

14 R0 <-> <address> swap the contents of R0 with the contents of a memory cell. The memory cell used is the one pointed to by thedata cell

15 R1 <-> <address> swap the contents of R1 with the contents of a memory cell. The memory cell used is the one pointed to by thedata cell

16 Ring the bell!17 Print R0 as an ASCII cha

The 8006

Example CodeSomething Simpleish

1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041424344454647484950

// LeapYear Function z3377034// written by Damon Stacey (Griffiths) and Kirsty Nitschke// 15 March 2011// to receive a year as input and output a 1 or 0 depending on if its a leap year

#include <stdio.h>#include <stdlib.h>#include <assert.h>

#define ERROR 123456789#define IS_LEAP_YEAR 1#define ISNT_LEAP_YEAR 0 #define START_GREGORIAN_CALENDAR 1582int isLeapYear (int year);

int main (int argc, char *argv[]) { int year; printf ("Please enter the year you would like to test \n"); scanf ("%d", &year); assert (year >= START_GREGORIAN_CALENDAR); int leapYear = isLeapYear (year); if (leapYear == 0) { printf ("That year is not a leap year \n"); } else if (leapYear == 1) { printf ("That is a leap year \n"); } else { printf ("ERROR \n"); } return EXIT_SUCCESS;}

int isLeapYear (int year) { int leapYear = ERROR; if ((year % 4000) == 0) { leapYear = ISNT_LEAP_YEAR; } else if ((year % 400) == 0) { leapYear = IS_LEAP_YEAR; } else if ((year % 4) == 0) { if ((year % 100) == 0) { leapYear = ISNT_LEAP_YEAR; } else { leapYear = IS_LEAP_YEAR; } } else { leapYear = ISNT_LEAP_YEAR; } return leapYear;}

A Recursive Function

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

61 of 77 20/06/11 10:10 AM

Page 62: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 2 3 4 5 6 7 8 910111213141516171819202122232425

//Written by 2008 COMP1917... probably by Buckland #include <stdio.h> #include <stdlib.h> int sumToN (int n); int main (int argc, char * argv[]) { int number; printf("Enter n\n"); scanf ("%d", &number); printf("sumToN (%d) = %d\n", number, sumToN (number)); return EXIT_SUCCESS; } int sumToN (int n) { int sum; if (n==0) { sum = 0; } else { sum = n + sumToN (n-1); } return sum; }

BMP writing

Week 7 Prac… Modify the following program to create a bmp file of a black and white chess board. The board must be 512x512 pixels in size. Itshould consists of n x n black and white squares in chequerboard fashion (like black and white tiles on a kitchen floor). The bottom right handsquare must be white. You can assume n will be a factor of 512.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

/* * week6.c * create a 512x512 BMP of a chessboard, with user specified size (in pixels) * of the black and white squares on the board. bottom right square must be white. * * Original Black Square printer Created by Richard Buckland on 14/04/11. * Modified by Damon Stacey on 2011-04-20 to print an alternating black white square board… :D * Copyright 2011 Licensed under Creative Commons SA-BY-NC 3.0. * */#include <stdio.h> #include <stdlib.h> #include <assert.h> #define BYTES_PER_PIXEL 3 #define BITS_PER_PIXEL (BYTES_PER_PIXEL*8) #define NUMBER_PLANES 1 #define PIX_PER_METRE 2835 #define MAGIC_NUMBER 0x4d42 #define NO_COMPRESSION 0 #define OFFSET 54 #define DIB_HEADER_SIZE 40 #define NUM_COLORS 0 #define SIZE 512 #define BMP_FILE "chess.bmp" typedef unsigned char bits8; typedef unsigned short bits16; typedef unsigned int bits32; void writeHeader (FILE *file); int main(int argc, char *argv[]) { FILE *outputFile; int squareSize; outputFile = fopen(BMP_FILE, "wb"); assert ((outputFile!=NULL) && "Cannot open file"); writeHeader(outputFile); printf ("Enter square size (must be a factor of %d): \n", SIZE); scanf ("%d", &squareSize); assert (SIZE % squareSize == 0); int numBytes = (SIZE * SIZE * BYTES_PER_PIXEL); int pos = 0; bits8 byte; while (pos < numBytes) { if (((pos)/(SIZE * squareSize * 3) % 2) == 1) { if ((((pos)/(3 * squareSize)) % 2) == 0) { byte = 255; fwrite (&byte, sizeof byte, 1, outputFile); } else if ((((pos) / (3 * squareSize)) % 2) == 1) { byte = 0; fwrite (&byte, sizeof byte, 1, outputFile); }

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

62 of 77 20/06/11 10:10 AM

Page 63: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129

} else if (((pos) / (SIZE * squareSize * 3) % 2) == 0) { if ((((pos) / (3 * squareSize)) % 2) == 0) { byte = 0; fwrite (&byte, sizeof byte, 1, outputFile); } else if ((((pos) / (3 * squareSize)) % 2) == 1) { byte = 255; fwrite (&byte, sizeof byte, 1, outputFile); } } pos++; } fclose(outputFile); return EXIT_SUCCESS; } void writeHeader (FILE *file) { assert(sizeof (bits8) == 1); assert(sizeof (bits16) == 2); assert(sizeof (bits32) == 4); bits16 magicNumber = MAGIC_NUMBER; fwrite (&magicNumber, sizeof magicNumber, 1, file); bits32 fileSize = OFFSET + (SIZE * SIZE * BYTES_PER_PIXEL); fwrite (&fileSize, sizeof fileSize, 1, file); bits32 reserved = 0; fwrite (&reserved, sizeof reserved, 1, file); bits32 offset = OFFSET; fwrite (&offset, sizeof offset, 1, file); bits32 dibHeaderSize = DIB_HEADER_SIZE; fwrite (&dibHeaderSize, sizeof dibHeaderSize, 1, file); bits32 width = SIZE; fwrite (&width, sizeof width, 1, file); bits32 height = SIZE; fwrite (&height, sizeof height, 1, file); bits16 planes = NUMBER_PLANES; fwrite (&planes, sizeof planes, 1, file); bits16 bitsPerPixel = BITS_PER_PIXEL; fwrite (&bitsPerPixel, sizeof bitsPerPixel, 1, file); bits32 compression = NO_COMPRESSION; fwrite (&compression, sizeof compression, 1, file); bits32 imageSize = (SIZE * SIZE * BYTES_PER_PIXEL); fwrite (&imageSize, sizeof imageSize, 1, file); bits32 hResolution = PIX_PER_METRE; fwrite (&hResolution, sizeof hResolution, 1, file); bits32 vResolution = PIX_PER_METRE; fwrite (&vResolution, sizeof vResolution, 1, file); bits32 numColors = NUM_COLORS; fwrite (&numColors, sizeof numColors, 1, file); bits32 importantColors = NUM_COLORS; fwrite (&importantColors, sizeof importantColors, 1, file); }

Something playing with arrays

Something playing with strings

Balanced Brackets example Code:

1 2 3 4 5 6 7 8 910111213

//this Program recieves a string input and tests if all brackets are balanced//I.e. it recieves a file and outputs if the brackets in it are//balanced//written by Damon Stacey (Griffiths)#include <stdio.h>#include <stdlib.h>#include <string.h>

#include "Stack.h"

#define MAX_STRING_LENGTH 10000#define TRUE 1#define FALSE 2

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

63 of 77 20/06/11 10:10 AM

Page 64: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

14151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

int checkBalanced(char *string);

int main (int argv, char *argc[]) {

char input = 0; char inputString[MAX_STRING_LENGTH]; int i = 0; while ((i < MAX_STRING_LENGTH) && (input != EOF)) { input = getchar(); inputString[i] = input; i++; } int theTruth; theTruth = checkBalanced(inputString); if (i==1) { printf ("Balanced\n"); } else if (theTruth == TRUE) { printf ("Unbalanced\n"); } else { printf ("Balanced\n"); } return EXIT_SUCCESS; }

int checkBalanced(char *string) { Stack pez = newStack(); int balance = TRUE; int i = 0;

while ((i < strlen(string)) && (balance == TRUE)) { //if its an opening bracket add that type to the stack.. :D if (string[i] == '(') { push(pez, '('); } else if (string[i] == '{') { push(pez, '{'); } else if (string[i] == '[') { push(pez, '[');//if its a closing bracket, check its valid to drop one! if not return balanced is false } else if (string[i] == ')') { if ((getNumItems(pez) > 0) && (top (pez) == '(')) { pop(pez); } else { balance = FALSE; } } else if (string[i] == '}') { if ((getNumItems(pez) > 0) && (top (pez) == '{')) { pop(pez); } else { balance = FALSE; } } else if (string[i] == ']') { if ((getNumItems(pez) > 0) && (top (pez) == '[')) { pop(pez); } else { balance = FALSE; } } i++; }

if (getNumItems(pez) > 0) { balance = FALSE; } return balance;}

Note it uses the following Stack setup

1 2 3 4 5 6 7 8 91011121314151617

/* * Stack.h * an ADT for a bounded stack of characters * * Created by Richard Buckland on 2/05/11. * Copyright 2011 Licensed under Creative Commons SA-BY-NC 3.0. * */ typedef struct _stack *Stack; Stack newStack (void);int push (Stack s, char elt);char top (Stack s);int pop (Stack s);int getMaxSize (Stack s);int getNumItems (Stack s);

Stack.c

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

64 of 77 20/06/11 10:10 AM

Page 65: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354

//Stack.c#include <stdlib.h>#include <stdio.h>#include <assert.h> #include "Stack.h" #define MAX_STRING_LENGTH 10000 struct _stack { int numItems; char array[MAX_STRING_LENGTH];}; Stack newStack (void) { Stack aStack = malloc(sizeof(struct _stack)); assert (aStack != NULL); aStack->numItems = 0; return aStack;} int push (Stack s, char elt){ int i = getNumItems(s); assert(i < 1000); s->array[i+1] = elt; return EXIT_SUCCESS;} char top (Stack s){ int i = getNumItems(s); char topOfStack = s->array[i]; return topOfStack;} int pop (Stack s){ int i = getNumItems(s); assert(i >= 0); s-> array[i] = 0; s-> numItems--; return EXIT_SUCCESS;} int getMaxSize (Stack s){ int maxSize = sizeof((*s).array); return maxSize;} int getNumItems (Stack s){ int i = s->numItems; return i;}

Linked List Example (By Mathew Moss)

The above Stack.c rewritten to work with a linked list.

1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031323334

/* * List.h * * Matthew Moss, mdmo552 * Fri13Harp, Tutor: Rowan Katekar * 20/5/2011 * Implementation of a Linked List ADT * */ typedef char item;typedef struct _list *List;

List newList (void);/* Will crash on out of memory errors */

int getLength (List l);/* Returns 0 for an empty list */

item getItem (List l, int index);/* List is indexed from 0 *//* Indexes outside the list will cause undefined behavior */

void appendItem (List l, item i);/* Will crash on out of memory errors */

void removeItem (List l, int index);/* List is indexed from 0 *//* Indexes outside the length will cause undefined behavior */

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

65 of 77 20/06/11 10:10 AM

Page 66: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

353637

void disposeList (List l);/* Following disposing, list pointer should be set to NULL */

List.c: the actual code is deleted to decrease the difficulty of the exam.

List.c functions ideas:

newList: malloc a list, initiallize the values of the list. Care about the address of the pointer pointing to, they should be NULL

appendItem: walk through the list using while loop and stop when you get to the right position

note:care about the special case when the list have no items, it's different when you have items in the list beforehand since you need to change thepointer "first" to point to that item.

getItem: the same procedure as your appendItem but the only difference is you need to get the content of that node rather than appendingitems to it.

deleteItem: two cases, delete from the front of the list or delete in the middle of the list. If you want to delete an item from the front of the list,you need to change the pointer "first", point to the new item then free the one you want to delete. On the other hand, you need to loop throughthe list and you stop right before the node you want to delete, you change the pointer next of this node to the guy next to the node you want todelete then you free the current node.(in this case, you need to keep tracking the current one)

Server with file IO

Im including a work in progress.. it is broken and slight problems as ive not put enough work into it... :(

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

//Server For outputting 3D images of the blue mountains//Version 1.0//By Damon Stacy - SERVER BY RICHARD BUCKLAND

#include <stdlib.h>#include <stdio.h>#include <assert.h>#include <netinet/in.h>#include <string.h>#include <unistd.h>#include "pixelColor.h"#include "pixelColor.c"

typedef unsigned char bits8;typedef unsigned short bits16; typedef unsigned int bits32;

typedef struct _requestData { int zoom; double x; double y; char type;} requestData;

#define ERROR 01234567#define SIMPLE_SERVER_VERSION 1.0#define REQUEST_BUFFER_SIZE 1000#define DEFAULT_PORT 7191#define NUMBER_OF_PAGES_TO_SERVE 20000

#define MAX_ITERATIONS 1000 #define NUM_Y_PIXELS 512 #define NUM_X_PIXELS 512#define HALF 0.5

#define BMP_HEADER_SIZE 54

#define END_WHILE_COMPLETE 0#define INFINITE_ITERATIONS 987654321

#define BYTES_PER_PIXEL 3#define BITS_PER_PIXEL (BYTES_PER_PIXEL*8)#define NUMBER_PLANES 1#define PIX_PER_METRE 2835#define MAGIC_NUMBER 0x4d42#define NO_COMPRESSION 0#define OFFSET 54#define DIB_HEADER_SIZE 40#define NUM_COLORS 0

#define SIZE 512

#define WIDTH NUM_X_PIXELS#define HIEGHT NUM_Y_PIXELS

#define BMP_FILE_REQUEST 'X'

unsigned char stepsToRed (int steps); unsigned char stepsToBlue (int steps); unsigned char stepsToGreen (int steps);

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

66 of 77 20/06/11 10:10 AM

Page 67: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159

requestData pullData (char request[]);

int waitForConnection (int serverSocket); int makeServerSocket (int portno);

void serveBMPHeader (int socket); int serveBMP (int socket, double xInput, double yInput, int zoomInput);

void serveHTML (int socket);

int iterator (double y, double x); void testIterator (void); unsigned long twoToPower (int number); void testTwoToPower (void);

int main (int argc, char *argv[]) { // testTwoToPower(); int number = 32; if (twoToPower(number) <= 0) { printf("You are on a 32 bit system and you will be unable to " "zoom in any further than 30 due to restrictions on data" " storage, sorry for any inconveniance\n"); } printf ("************************************\n"); printf ("Starting simple server %f\n", SIMPLE_SERVER_VERSION); printf ("Serving The Mandelbrot since 2011\n"); int serverSocket = makeServerSocket (DEFAULT_PORT); printf ("Access this server at http://localhost:%d/\n", DEFAULT_PORT); printf ("************************************\n"); char request[REQUEST_BUFFER_SIZE]; int numberServed = 0; while (numberServed < NUMBER_OF_PAGES_TO_SERVE) { printf ("*** So far served %d pages ***\n", numberServed); int connectionSocket = waitForConnection (serverSocket); // wait for a request to be sent from a web browser, open a new // connection for this conversation // read the first line of the request sent by the browser int bytesRead; bytesRead = read (connectionSocket, request, (sizeof request)-1); assert (bytesRead >= 0); // were we able to read any data from the connection? // print entire request to the console printf (" *** Received http request ***\n %s\n", request); //send the browser a simple html page using http printf (" *** Sending http response ***\n"); requestData theRequest = pullData (request); char typeOfRequest = (pullData(request)).type; if (typeOfRequest = BMP_FILE_REQUEST) { printf ("BMP File Requested\n"); } else { printf("Web Server Requested\n"); } if (typeOfRequest == BMP_FILE_REQUEST) { double x = theRequest.x; double y = theRequest.y; int zoom = theRequest.zoom; //serveBMPHeader(connectionSocket); serveBMP(connectionSocket, x, y, zoom); } else { serveHTML (connectionSocket); } // close the connection after sending the page- keep aust beautiful close(connectionSocket); numberServed++; if (typeOfRequest = BMP_FILE_REQUEST) { printf ("BMP File Sent\n"); } else { printf("Web Server Sent\n"); } } // close the server connection after we are done- keep aust beautiful printf ("** shutting down the server **\n"); close (serverSocket); return EXIT_SUCCESS; }

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

67 of 77 20/06/11 10:10 AM

Page 68: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256

requestData pullData (char request[0]) { requestData theRequest; sscanf(request, "GET /%c-%lf-%lf-%d", &theRequest.type, &theRequest.x, &theRequest.y, &theRequest.zoom); return theRequest;

}// start the server listening on the specified port numberint makeServerSocket (int portNumber) { // create socket int serverSocket = socket (AF_INET, SOCK_STREAM, 0); assert (serverSocket >= 0); // error opening socket // bind socket to listening port struct sockaddr_in serverAddress; bzero ((char *) &serverAddress, sizeof (serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_addr.s_addr = INADDR_ANY; serverAddress.sin_port = htons (portNumber); // let the server start immediately after a previous shutdown int optionValue = 1; setsockopt ( serverSocket, SOL_SOCKET, SO_REUSEADDR, &optionValue, sizeof(int) ); int bindSuccess = bind ( serverSocket, (struct sockaddr *) &serverAddress, sizeof (serverAddress) ); assert (bindSuccess >= 0); // if this assert fails wait a short while to let the operating // system clear the port before trying again return serverSocket;}

// wait for a browser to request a connection,// returns the socket on which the conversation will take placeint waitForConnection (int serverSocket) { // listen for a connection const int serverMaxBacklog = 10; listen (serverSocket, serverMaxBacklog); // accept the connection struct sockaddr_in clientAddress; socklen_t clientLen = sizeof (clientAddress); int connectionSocket = accept ( serverSocket, (struct sockaddr *) &clientAddress, &clientLen ); assert ((connectionSocket >= 0) && "Port has been taken by another application"); // error on accept return (connectionSocket);}

unsigned long twoToPower (int number) { int counter = 2; unsigned long newNum = 2; while (counter <= number) { newNum = newNum*2; counter++; } return newNum;}

void serveBMPHeader (int socket) { char *httpResponseHeaderForBmp;

int sizeOfImage = WIDTH * HIEGHT * BYTES_PER_PIXEL; printf("sending %d bytes\n", sizeOfImage + OFFSET); // As we have been requested by the HTTP protocol, respond with a //HTTP response header, to tell them what we are now sending httpResponseHeaderForBmp = "HTTP/1.0 200 OK\r\n"

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

68 of 77 20/06/11 10:10 AM

Page 69: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353

"Content-Length: %d\r\n" "Content-Txpe: image/bmp\r\n" "\r\n", sizeOfImage + OFFSET; printf ("about to send=> %s\n", httpResponseHeaderForBmp); write (socket, httpResponseHeaderForBmp, strlen (httpResponseHeaderForBmp)); printf ("sent\n");

// now send the contents of the bmp file to be displayed //First we send the BMP header which is as follows //Note this is a variation from // Black Square printer Created by Richard Buckland on 14/04/11. // For the 2011s1 COMP1917 Course

assert(sizeof (bits8) == 1); assert(sizeof (bits16) == 2); assert(sizeof (bits32) == 4); bits16 bmIdentifier = MAGIC_NUMBER; write (socket, &bmIdentifier, sizeof bmIdentifier); bits32 fileSize = OFFSET + (WIDTH * HIEGHT * BYTES_PER_PIXEL); write (socket, &fileSize, sizeof fileSize); bits32 reserved = 0; write (socket, &reserved, sizeof reserved); bits32 offset = OFFSET; write (socket, &offset, sizeof offset); bits32 dibHeaderSize = DIB_HEADER_SIZE; write (socket, &dibHeaderSize, sizeof dibHeaderSize); bits32 width = WIDTH; write (socket, &width, sizeof width); bits32 height = HIEGHT; write (socket, &height, sizeof height); bits16 planes = NUMBER_PLANES; write (socket, &planes, sizeof planes); bits16 bitsPerPixel = BITS_PER_PIXEL; write (socket, &bitsPerPixel, sizeof bitsPerPixel); bits32 compression = NO_COMPRESSION; write (socket, &compression, sizeof compression); bits32 imageSize = (WIDTH * HIEGHT * BYTES_PER_PIXEL); write (socket, &imageSize, sizeof imageSize); bits32 hResolution = PIX_PER_METRE; write (socket, &hResolution, sizeof hResolution); bits32 vResolution = PIX_PER_METRE; write (socket, &vResolution, sizeof vResolution); bits32 numColors = NUM_COLORS; write (socket, &numColors, sizeof numColors); bits32 importantColors = NUM_COLORS; write (socket, &importantColors, sizeof importantColors); // printf("Header sent\n");}

int serveBMP (int socket, double xInput, double yInput, int zoomInput) { int sizeOfImage = WIDTH * HIEGHT * BYTES_PER_PIXEL; printf("Hello\n"); printf("sizeOfArrays is %lf MB\n", ((sizeOfImage*2.0)/1024)/1024); int textureData[WIDTH][HIEGHT]; int heightData[WIDTH][HIEGHT]; int textureDataRed[WIDTH][HIEGHT]; int textureDataBlue[WIDTH][HIEGHT]; int textureDataGreen[WIDTH][HIEGHT];

printf("Hello\n"); int x = xInput; int y = yInput; int depth = zoomInput; //Open all relevant files FILE *inputTexture; FILE *inputHeightOne; FILE *inputHeightTwo; char format[] = "3DViewer/%d,%dTexture.bmp"; char filename[sizeof format+100]; sprintf(filename, format, x, y); inputTexture = fopen(filename,"r"); //(Needs to use the x y and depth values) strcpy(format, "3DViewer/%d,%dheight1.bmp"); sprintf(filename, format, x, y); inputHeightOne = fopen(filename,"r");

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

69 of 77 20/06/11 10:10 AM

Page 70: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450

strcpy(format, "3DViewer/%d,%dheight2.bmp"); sprintf(filename, format, x, y); inputHeightTwo = fopen(filename,"r");

//making sure its found the files assert ((inputTexture != NULL) && "Cannot open texture"); assert ((inputHeightOne != NULL) && "Cannot open Height Data"); assert ((inputHeightTwo != NULL) && "Cannot open all Height Data"); //Write Header from texture input as my header is currently broken.. ? //and count through the header of the hieght files int i = 0; int temp = 0; int temp2 = 0; while (i<BMP_HEADER_SIZE) { temp = fgetc (inputTexture); write(socket, &temp, sizeof(unsigned char)); temp2 = fgetc (inputHeightOne); temp2 = fgetc (inputHeightTwo); i++; }

//Get All the data from original texture i = 0; int width = 0; int height = 0; while (height <= HIEGHT) { width = 0; while (width <= WIDTH) { temp = fgetc(inputTexture); textureData[width][height] = temp; //(Moving through 2 more data points, as this should be greyscale) //I.e the same for every 3 pixels temp = fgetc(inputTexture); temp = fgetc(inputTexture); width+=3; } height++; }

//At this point the entire image is only grey //Get All the data about the heights relative to each pixel //using the formula (256 * infofromheight1file * ...height2file) - 1000; //provided by Richard Buckland i = 0; width = 0; height = 0; while (height <= HIEGHT) { width = 0; while (width <= WIDTH) { temp = fgetc(inputHeightOne); temp2 = fgetc(inputHeightTwo); heightData[width][height] = (256 * temp * temp2) - 1000; //(Moving through 2 more data points, as this should be greyscale) //I.e the same for every 3 pixels? Might be wrong and //why this code isnt working.. temp = fgetc(inputHeightOne); temp = fgetc(inputHeightTwo); width+=3; } height++; }

//create the data for the right eye (Blue stuff) //to redo... as my last method was wrong... o.O //create the date for the left eye (Red Stuff) //to redo... as my last method was wrong... o.O //combine them into the original array //to redo... as my last method was wrong... o.O

i = 0; width = 0; height = 0; while (height <= HIEGHT) { width = 0; while (width <= WIDTH) { //GREEN temp = (textureData[width][height] % 255); write(socket, &temp, sizeof(unsigned char)); //BLUE temp = (textureData[width][height] % 255); write(socket, &temp, sizeof(unsigned char)); //RED temp = (textureData[width][height] % 255); write(socket, &temp, sizeof(unsigned char)); width+=3; } height++; } //Close the files used... fclose(inputTexture); fclose(inputHeightOne); fclose(inputHeightTwo);

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

70 of 77 20/06/11 10:10 AM

Page 71: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502

return EXIT_SUCCESS;}

void serveHTML (int socket) { char* message; // first send the http response header // (if you write stings one after another like this on separate // lines the c compiler kindly joins them togther for you into // one long string) message = "HTTP/1.0 200 OK\r\n" "Content-Type: text/html\r\n" "\r\n"; printf ("about to send=> %s\n", message); write (socket, message, strlen (message)); // now send the contents of the web page to be displayed message = "<HTML>\n"; printf ("about to send=> %s\n", message); write (socket, message, strlen (message)); message = "<script " "src=\"https://openlearning.cse.unsw.edu.au/site_media/viewer/tile.3d.2.js\"" "></script> \n"; printf ("about to send=> %s\n", message); write (socket, message, strlen (message)); message = "</HTML>\n"; printf ("about to send=> %s\n", message); write (socket, message, strlen (message));}

void testTwoToPower (void) {

assert (twoToPower (2) == 4); assert (twoToPower (3) == 8); assert (twoToPower (4) == 16); assert (twoToPower (5) == 32); assert (twoToPower (6) == 64); assert (twoToPower (7) == 128); assert (twoToPower (8) == 256); assert (twoToPower (9) == 512); }

Something playing with bitwise operators

TablesAcii->Hex->Decimal

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

71 of 77 20/06/11 10:10 AM

Page 72: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Decimal->Hex-> Binary

FROM: http://h71000.www7.hp.com/doc/73final/4515/4515pro_038.html

B.1 Hexadecimal to Decimal

For each integer position of the hexadecimal value, locate the corresponding column integer and record its decimal equivalent in the conversion

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

72 of 77 20/06/11 10:10 AM

Page 73: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

table. Add the decimal equivalent to obtain the decimal value.

For example:

D0500AD0 (hex) = ?(dec)

D0000000 = 3,489,660,928

500000 = 5,242,880

A00 = 2,560

D0 = 208

D0500AD0 = 3,494,906,576

B.2 Decimal to Hexadecimal

To determine the hexadecimal equivalent of a given decimal value, perform the following steps: In the conversion table, locate the largest decimalvalue that does not exceed the decimal number to be converted. Record the hexadecimal equivalent, followed by the number of zeros thatcorresponds to the integer column minus 1. Subtract the table decimal value from the decimal number to be converted. Repeat steps 1 to 3 until thesubtraction balance equals zero. Add the hexadecimal equivalents to obtain the hexadecimal value. For example:

22,466 (dec) = ?(hex)

20,480 = 5000

1,792 = 700

192 = C0

2 = 2

22,466 = 20480 + 1792 + 192 + 2 = 57C2

B.3 Powers of 2 and 16 This section lists the decimal values of powers of 2 and 16. These values are useful in converting decimal numbers tohexadecimal.

Powers of 2 Powers of 162^n n 16^n n

256 8 1 0512 9 16 11024 10 256 22048 11 4096 34096 12 65536 48192 13 1048576 516384 14 16777216 632768 15 268435456 765536 16 4294967296 8131072 17 68719476736 9262144 18 1099511627776 10524288 19 17592186044416 111048576 20 281474976710656 122097152 21 4503599627370496 134194304 22 72057594037927936 148388608 23 1152921504606846976 1516777216 24

Variable types and Thier size and escape chars

Type EscapeCommand Accepted inputs Size in bytes

ASCII character %c char (signed and unsigned) ORShort 1 Byte

int in decimal %d int At least as big as char (usually at least 2 bytes)

unsigned int in decimal %u unsigned int At least as big as short (usually at least 4 bytes - 32bits)

long in decimal %l long At least as big as intunsigned long in decimal %lu unsigned longint or unsigned int in hexadecimal %x int, unsigned int

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

73 of 77 20/06/11 10:10 AM

Page 74: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

long or unsigned long inhexadecimal %lx long, unsigned long

A fractional value in decimal to afloat %f float Unspecified in the C standard (usually 4 bytes)

A fractional value to a double %lf double Unspecified (at least as big as float, usually 8 bytes)

Escape Sequences

Escape Sequence Represents\a Bell (alert)\b Backspace\f Formfeed\n New line\r Carriage return\t Horizontal tab\v Vertical tab\' Single quotation mark\ " Double quotation mark\ \ without the spacebetween them

Backslash

\? Literal question mark\ ooo ASCII character in octal notation\x hh ASCII character in hexadecimal notation

\x hhhh Unicode character in hexadecimal notation if this escape sequence is used in a wide-character constant or a Unicode stringliteral. For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The Chinese character for one is \x4e00".

Binary To Hex To Octal To Decimal table (SHORTER)

Previous Chapter | Next Chapter

Chapter 47 aka A new Tomorrow

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

74 of 77 20/06/11 10:10 AM

Page 75: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

Richard encourages us to join the ACS (Australian Computer Society)

Revision:Rules

We’ve been talking about rules, and how as you add more rules, things become more complex much faster than the rate at which you’readding rules.

E.g. The card game Set is an example of this, it’s very similar to the confusing game Richard played on the board where he wasdrawing circles, triangles, and squares. In this game each card has a colour, a shape, a pattern and a number, and to get a set (of three)each attribute must either be all the same or all different. Essentially this game doesn’t have many more rules than noughts and crossesbut it can take much longer to find a solution.

Richard played us a piece of music by eccles and bluebottle which related to the music we made in the first week based on the game ofnoughts and crosses we played.

Openness

Openness is a very good thing.Richard made the 2008 lectures available on youtube and now gets thousands of emails from less privileged people who weren’t able togo to unishowing us the source code for everything, eg all the assignments etc and allowing people into the trusted group, allowed everyone tohelp fix the mistakes and make things less ambiguous and ultimately work better. (note: to get into the trusted group, add your name tothe trusted group page)Richard talked about intellectual property and the 2 different approaches to knowledge:

the “old fashion scientific approach”, that knowledge is to be shared and used collaboratively to push back the boundaries ofhuman knowledgethe newer approach that knowledge is something to be kept to yourself and locked away so you can make money out of it

Richard very clearly believes in the first approach but wants us to think about our own opinion

Points of View

Different Points of view can change everythingRichard showed us a picture of a cube drawn across a doorway that looked like it way in front of the doorway but way actually drawnall down the corridor and from a particular point looked like a cubethe movie Colonel Blimp, has a starting scene that makes you form opinions of people, then flashes back into the life of one character,and then replays the starting scene, and it’s so different the second time because you now have empathy for another character.

Dissent

Hopes that rather than just agreeing with him because we like him, we’re secretly disagreeing with everything he says and questioning itused the movie The Third Wave as an example, where a teacher managed to control his class in a similar way to Hitler, because he waslikeable and brought it on graduallyQuote by Nietzsche “The surest way to corrupt a youth is to instruct him to hold in higher esteem those who think alike than those who thinkdifferently”

The Future1927

teaches us data structures and algorithmslearn more of the science in computer sciencemove away from project managementfocuses on how to make small fragments of code work really really well

2911

teaches us to become designers, how to come up with new ways to solve problemsfocuses on going from problem to solution, and the many ways you can do it

9447

security engineering workshopamazing inspiring course but each year Richard worries it won’t run the next year because the people who run it are very sort after and do thisout of the goodness of their hearts

Reflection On reflection (why do we have pointers?)Can’t structure data without pointersCan’t do pass by reference without pointerspointers give you indirection or reflection on reflectionwithout pointers you can only deal with the names of things and everything is very literal e.g.

the castle, Dale Kerrigan speaks without “pointers”, doesn’t use pronouns very muchAbbot and Costello – “Who’s on first?”Lewis Carrol – “The White Knight’s Poem”radio lab – talking about a man of age 27, who’s only just learnt that things had names, and could now talk everything, and refer to

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

75 of 77 20/06/11 10:10 AM

Page 76: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

everything rather than just doing things

Previous Chapter | Next Chapter

Revision SessionMemory

Every cell(or an address) can have a value

Address(pointer) of x: &x

&x = 30 address of x is 30

Value of x: x

x = 50 value of x is 50

Goto the address number with the value of x: *x(DEREFERENCING)

if x was 67 then *x means 'goto the address with the value of x(ie 67) then read its contents.Some more complex examples:

this could potentially cause issues

int is usually 4 bytes but pointer value is the first byte of the 4 bytes it is pointing to.**x

double dereference twice may make your compiler frown although it may still workN.B. x has to be declared as a pointer initially for it to work. Hence int *x OR you can cast it.(ie put the bracket)**(int *)x(int* x) reads x is a pointer to the number which is x

Few other ways of doing pointing->:ADT*[]: array

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

76 of 77 20/06/11 10:10 AM

Page 77: Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1 - …openlearning/2011s1/textbook.pdf · 2011. 6. 20. · Abstraction The art of seeing things at different levels. The lecturer

FunctionUsually as many as inputs as desired with single outputusing dereferencing and pointer, original value can be kept same and function can create its own version of the value(useful in abstract datatype)

Eg. sdinger(int*m) { (*m)++; return( (*m)*42 )} As this is a pointer, we can change the input eg. when calling function:sdinger(&x) ie we are inputting the address value. in the function we need convert the address into a value(ie derefence) so *m is usedto do that.

Arrayis a special case in Cpassing array to a function passes the address of an array; usually in other data types content is passed

Linked List1. Draw a Picture2. Form a struct - one for the START node and other for SUBSEQUENT nodes3. typedef list *List( ADT enabling declaration) and node in similar fashion as well

Append Function

create the nodescan along the list until node with no info is found NULLChange NULL pointe to point to the new node

ProtoType: void append(L3ist l, int newData) Don't forget to check if the start exists yet

1. Allocate Memory2. Assert list is not NULL3. Next node to be NULL4. Write Data for the node5. Move along the node until the final node is reached.6. Write prepared new node into this last node

Text Bookdont put too much code that can be transported Put egs. and snippets

Examboth parts are on a computer, we will have a text editor for the theory section. there will be 'run basic tests' for the prac exam

Prac Exam(1.5 Hours): Compiler YES, Textbook NO. Pass or Fail SystemTheory Exam(3 Hours): Compiler NO, Textbook YES.

Theory exam uses rbnc -Richard Buckland's Neuronal Compiler

Previous Chapter

UNSW OpenLearning Privacy and Terms of Use Cite OL content

Your use of the OpenLearning site and course materials is subject to our Creative Commons License and other terms of use.

Combined TextBook - Comp1917 2011s1 - TextBook - 2011s1... https://openlearning.cse.unsw.edu.au/Comp1917/2011s1/Tex...

77 of 77 20/06/11 10:10 AM