Lecture 1: Introduction Programming Fundamentals Gorka Guardiola - - PowerPoint PPT Presentation

lecture 1 introduction
SMART_READER_LITE
LIVE PREVIEW

Lecture 1: Introduction Programming Fundamentals Gorka Guardiola - - PowerPoint PPT Presentation

Lecture 1: Introduction Programming Fundamentals Gorka Guardiola LS, GSYC October 24, 2011 Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 1 / 32 (cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This


slide-1
SLIDE 1

Lecture 1: Introduction

Programming Fundamentals Gorka Guardiola

LS, GSYC

October 24, 2011

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 1 / 32

slide-2
SLIDE 2

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 2 / 32

slide-3
SLIDE 3

What does a computer do?

General purpose machine to process information:

◮ Take information (input) ◮ Process it ◮ Store it/retrieve it ◮ Produce information (output)

PC/Computers around us everywhere

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 3 / 32

slide-4
SLIDE 4

What is a computer?

MEMORY MOUSE KEYBOARD HARD DISK CPU +

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 4 / 32

slide-5
SLIDE 5

Elements of a Computer

Hardware: physical elements

◮ Input devices ◮ Output devices ◮ Central Processing Unit (CPU) ◮ Main memory ◮ Secondary storage (disks)

Software: Logical elements, programs This subject is about making software

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 5 / 32

slide-6
SLIDE 6

Encoding Information

Bit: 0 / 1 What can be represented as bits?

◮ Numbers ◮ Text ◮ Programs ◮ Images ◮ Sounds ◮ Images + sounds = video ◮ ... Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 6 / 32

slide-7
SLIDE 7

Bits and Bytes

8 bits are a byte, also called an octet How many distinct values can be represented with N bits?

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 7 / 32

slide-8
SLIDE 8

Information Units

Bit: Basic unit of information Byte: 8 bits Kilobyte: 1024 bytes, 210 bytes, the symbol is KB (KiB) Megabyte: 1024 KB, 220 bytes, the symbol is MB (MiB) Gigabyte: 1024 MB, 230 bytes, the symbol is GB (GiB) Terabyte: 1024 GB, 240 bytes, the symbol is TB (TiB) Petabyte, Exabyte...

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 8 / 32

slide-9
SLIDE 9

Information Units

Translate from one to another Divide/Multiply by 1024, 210

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 9 / 32

slide-10
SLIDE 10

Information Units: example

I have bought a hard disk with 512 MB of capacity how many 150 bytes files can I store in it?

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 10 / 32

slide-11
SLIDE 11

Information Units: example

512MB = 512 ∗ 1024 ∗ 1024 = 536870912 Bytes 536870912/150 = 3579139 files discount space for file names, etc.

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 11 / 32

slide-12
SLIDE 12

Information Encoding

How do we encode data with bits? → Asking yes/no questions(0/1) What about conventions, standards? → Same questions in the same

  • rder

The computer ignores the meaning of the association. The values

  • nly have meaning in the head of the programmer or user.

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 12 / 32

slide-13
SLIDE 13

Binary numbers

A number is mathematical object, a concept, an abstraction We represent it Computers use bits → base 2. Humans normally count in base 10 Base 16 (hexadecimal): useful when dealing with bytes

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 13 / 32

slide-14
SLIDE 14

Binary numbers

Decimal number Binary representation 1 1 2 10 3 11 4 100 5 101

Table: Binary representation, first six numbers

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 14 / 32

slide-15
SLIDE 15

Binary representation

101100

1 1 1 2 2 2 2 2 22 11 5 2 + + + + + 0*2^1 1*2^2 1*2^3 0*2^4 44 0*2^0 1*2^5 = 44

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 15 / 32

slide-16
SLIDE 16

Characters: letters, digits y symbols

What is a character? How do I respresent character? Different encodings: UTF-8, ASCII, ISO-8859...

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 16 / 32

slide-17
SLIDE 17

Texto

Plain text (UTF-8, ASCII, etc.) vs formatted text (DOC, ODT, etc.). Text editor (Scite, Gedit, etc.) vs. word processor (Word, OpenOffice, etc.). Programs are in plain text!

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 17 / 32

slide-18
SLIDE 18

Algorithm

Sequence of instructions to accomplish a task Can be expressed in natural language or pseudocode. Structured one point of entry, one point of exit with sequences, iterations and selections

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 18 / 32

slide-19
SLIDE 19

Sequence

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 19 / 32

slide-20
SLIDE 20

Selection

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 20 / 32

slide-21
SLIDE 21

Iteration

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 21 / 32

slide-22
SLIDE 22

Example of an algorithm

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 22 / 32

slide-23
SLIDE 23

Programs

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 23 / 32

slide-24
SLIDE 24

Programs Algorithms + Data Structures = Programs

Written in a programming language: formal, strict syntax Each programming language, different level of abstraction (compromise) Picky: high level of abstraction

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 24 / 32

slide-25
SLIDE 25

Instructions

CPU executes machine code. Each CPU has a (similar) set of operations:

◮ Arithmetic (sum, multiplication, etc.) ◮ Logical (comparisons, etc.) ◮ Moving data around

A program is a sequence of instructions The particular set depends on the concrete CPU (Intel, AMD, Motorola, IBM...).

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 25 / 32

slide-26
SLIDE 26

Abstraction levels (layers)

MACHINE CODE 2) print the pi number 3) write a carriage return 4) exit _TEXTsegmentbytepublic’CODE’ public_dt_ym1 pushax pushdx xorax,ax inal,dx

  • ral,al

xorax,ax movdx,TIMER0_CNT _dt_ym0procfar public_dt_ym0 0001011110001000100101110010101010101010101010101010101010 1001100110110101010110101000001111001010101010000101110010 1001010101010101010101000010000000011111011101011111110000 1010101010010101001010101001000000111101100101111111111111 NATURAL LANGUAGE (English) /* say hello to a great number */ program holapi; consts: Pi = 3.1415926; procedure main() { } write("Hola "); write(Pi); write("!"); writeeol(); PROGRAMMING LANGUAGE (picky) ASSEMBLY CODE 1) start by printing some form of greeting

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 26 / 32

slide-27
SLIDE 27

From program to executable

libraries CODE COMPILER OBJECT FILE OBJECT FILE LINKER EXECUTABLE FILE (BINARY) OBJECT FILE OBJECT FILE program SOURCE

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 27 / 32

slide-28
SLIDE 28

Programming

Steps:

1 Specify the problem 2 Set a plan 3 Implement the plan. 4 Test the implementation 5 Debug the implementation (80% of the time, most difficult).

Important: Little by little Successive refinement The first prototypes are always wrong.

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 28 / 32

slide-29
SLIDE 29

When trying to compile

Compilation errors Compilation warnings Execution errors Logical errors

Readable code → easier to fix errors

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 29 / 32

slide-30
SLIDE 30

Debugging

Make the problem reproducible Find systematically → trace by printing state at different points Difficult to fix → rewrite. Is the error where I think/what I think? After fixing, retest

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 30 / 32

slide-31
SLIDE 31

First steps with Picky

Comments Identifiers Blocks Reserved words (keyword). Literals Variables Statement Main program Subprogram Body see 01.programa.p

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 31 / 32

slide-32
SLIDE 32

Vocabulary

Indentation Legibility Interface Instantiate Implement

Gorka Guardiola (LS, GSYC) Lecture 1: Introduction October 24, 2011 32 / 32

slide-33
SLIDE 33

Lecture 2: Sets and elements

Programming Fundamentals Gorka Guardiola

LS, GSYC

October 7, 2011

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 1 / 20

slide-34
SLIDE 34

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 2 / 20

slide-35
SLIDE 35

Basic Sets in Picky

Data types:

◮ Set of homogeneous, elements with well defined operations. ◮ Cannot be mixed (strong typing). Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 3 / 20

slide-36
SLIDE 36

Data Types in Picky

Four sets of elements in Picky (primitive data types):

◮ Integer numbers: int ◮ Real numbers: float ◮ Chars: char ◮ Truth values: bool Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 4 / 20

slide-37
SLIDE 37

Basic Sets in Picky

Literals:

◮ Integers: 3 -5 ◮ Reals: 3.14 1.34E2 -1.00000E-04 ◮ Chars: ’a’ ’B’ ◮ Truth values: True False

see error.p

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 5 / 20

slide-38
SLIDE 38

Operators

Operators represent operations in Picky. Infix: between two (Picky), i.e. a + b Prefix (Polish notation) before the operands, i.e. + a b Postfix (reverse Polish notation) after the operands, i.e. a b +

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 6 / 20

slide-39
SLIDE 39

Numerical operators

float and int

◮ Sign: - + ◮ Addition: + ◮ Subtraction: - ◮ Multiplication: * ◮ Division: / ◮ Exponentiation: **

Only for int:

◮ Modulo (remainder): % Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 7 / 20

slide-40
SLIDE 40

Boolean operators

Complement/Negation: not Conjunction: and Disjunction: or

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 8 / 20

slide-41
SLIDE 41

Comparison operators/relational operators

Equal to: == Not equal to: ! = Greater than: > Greater or equal than: >= Less than: < Less or equal to: <= see edad.p

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 9 / 20

slide-42
SLIDE 42

Relational operators

The resulting value is of type bool Only compatible types can be comparated How do I compare floats? eps = 0.001; esPi = x >= Pi - eps and x <= Pi + eps; Can I compare chars? see real.p

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 10 / 20

slide-43
SLIDE 43

Expressions

Only one line Operations are evaluated in a concrete order: precedence. see expr.p

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 11 / 20

slide-44
SLIDE 44

Expressions

Can be grouped with parenthesis Evaluation is from the inside to the outside Spaces should be used for legibility

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 12 / 20

slide-45
SLIDE 45

Expressions: example

((3 ∗ 2)/(5 + 6 − (3 ∗ ∗2))) (6/(5 + 6 − (3 ∗ ∗2))) (6/(5 + 6 − 9)) (6/(11 − 9)) (6/2) 3

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 13 / 20

slide-46
SLIDE 46

Precedence table (all)

1 lower 2 or and 3 == ! = < > <= >= 4 (operation) + - 5 * / % 6 ** 7 (sign) + - 8 len not 9 higher Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 14 / 20

slide-47
SLIDE 47

Expressions

With same precedence are evaluated from left to right Operators associate to the left Parenthesize operators with same precedence

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 15 / 20

slide-48
SLIDE 48

Expressions

Example: It is a leap year if it is multiple of 4, not multiple of a 100 unless it is multiple of 400. see bisiesto.p

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 16 / 20

slide-49
SLIDE 49

Expressions: De Morgan Laws

not (a and b) ≡ (not a) or (not b) not (a or b) ≡ (not a) and (not b)

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 17 / 20

slide-50
SLIDE 50

Recomendations:

Minimize number of negations: Try not to minimize the number of non-negations Which one is easier to understand?

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 18 / 20

slide-51
SLIDE 51

Basic Sets in Picky

Explicit type conversion:

◮ int(3.14) ◮ float(3) ◮ char(3) ◮ int(’a’)

Not any type can be converted to any other. Allowed:

◮ int → float ◮ float → int ◮ Ordinal → int ◮ int → Ordinal Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 19 / 20

slide-52
SLIDE 52

Creating our own functions

Receives some parameters to make a calculation Returns only one value of the specified type

Gorka Guardiola (LS, GSYC) Lecture 2: Sets and elements October 7, 2011 20 / 20

slide-53
SLIDE 53

Lecture 3: Direct Solution Problems

Programming Fundamentals Gorka Guardiola

LSUB, GSYC, URJC

October 14, 2011

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 1 / 20

slide-54
SLIDE 54

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 2 / 20

slide-55
SLIDE 55

Start with simple direct solution problems

Apply a formula Simple steps, no decisions need to be taken

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 3 / 20

slide-56
SLIDE 56

Definition: Functions

Problem definition → function header What is it calculating → function name What does it need → function parameters Result → Type returned by the function

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 4 / 20

slide-57
SLIDE 57

Problem definition: Functions

Programming style in Picky: Function name has to correspond to the object returned e.g.: circlearea. Function and parameter identifiers are lowercase (all of them) Important to choose the name appropiatively Clarity of expression is important

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 5 / 20

slide-58
SLIDE 58

Problem definition: Functions

Argument: value given to the function when it is being called Parameter: identificator used to refer to the argument A function can have none, one or more parameters

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 6 / 20

slide-59
SLIDE 59

Problem definition: Functions

A function must always return one and only one value The value returned is of the function return type

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 7 / 20

slide-60
SLIDE 60

Problem solving: Functions

The solution is implemented in the body of the function The reserved word return makes the function return a value Structured programming: return always at the end of the function,

  • nly once

step by step circulo.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 8 / 20

slide-61
SLIDE 61

Subprograms

Functions are subprograms Subprograms solve subproblems Big programs difficult to understand/debug. Understanding a program means understanding each subprogram separately, which is easier. Divide and conquer.

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 9 / 20

slide-62
SLIDE 62

Constants

Problem parameters Constants instead of literals → less bugs Name instead of a number, less repetitions

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 10 / 20

slide-63
SLIDE 63

Declaration and definition

Declaration means stating something exists Define means to determine its value Scope: An object can only be used after it has been declared (when it starts existing) until the end of the program/subprogram where it was declared. Outside of its scope, it is not visible see pesos.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 11 / 20

slide-64
SLIDE 64

Problem attack: top-down

Based on optimism When we detect a subproblem we consider it solved and continue To progressively refine we can use empty or fake subprograms If you don’t have it, fake it!! Later we have to implement the subprogram This way the program/problem is broken into subprograms/subproblems naturally On each phase of the implementation we will have a prototype we can execute step by step cilindro.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 12 / 20

slide-65
SLIDE 65

Example top-down: student’s day

Problem: Student’s day

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 13 / 20

slide-66
SLIDE 66

Example top-down: student’s day

Student’s day

1 Wake up 2 Go to school 3 Go back home 4 Do the homework 5 Go to bed Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 14 / 20

slide-67
SLIDE 67

Example top-down: student’s day

D´ ıa de estudiante

1 Wake up 2 Go to school 3 Go back home 4 Do the homework 1

Programming homework

2

Algebra homework

5 Go to bed Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 15 / 20

slide-68
SLIDE 68

Example top-down: student’s day

D´ ıa de estudiante

1 Wake up 2 Go to school 3 Go back home 4 Do the homework 1 1

Read the chapter of the book

2

Start the weekly hand-in

2

Algebra homework

5 Go to bed Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 16 / 20

slide-69
SLIDE 69

Problem attack: bottom-up

Based on thinking in advance. Start with breaking the problem and thinking of all the elements needed Then we write the subprograms solving the simplest subproblems Combine them to solve more complex problems until we get to the solution Difficulty: some amount of intuition is needed to find the right elements (given by experience)

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 17 / 20

slide-70
SLIDE 70

Both have to be combined

  • Gorka Guardiola (LSUB, GSYC, URJC )

Lecture 3: Direct Solution Problems October 14, 2011 18 / 20

slide-71
SLIDE 71

Problem attack: simplification and generalization

1 Think the solution for a simple, particular case 2 Try it 3 Generalize it

program digitos.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 19 / 20

slide-72
SLIDE 72

Functions provided by Picky

1 acos(r: float): float 2 asin(r: float): float 3 atan(r: float): float 4 cos(r: float): float 5 exp(r: float): float 6 log(r: float): float 7 log10(r: float): float 8 pow(r: float): float 9 sin(r: float): float 10 sqrt(r: float): float 11 tan(r: float): float Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 3: Direct Solution Problems October 14, 2011 20 / 20

slide-73
SLIDE 73

Lecture 4: Selection Problems

Programming Fundamentals Gorka Guardiola

LS, GSYC, URJC

October 24, 2011

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 1 / 9

slide-74
SLIDE 74

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 2 / 9

slide-75
SLIDE 75

Selection Problems

Problems where a decision needs to be taken. We need control structures. e.g.: piece-wise functions like the sign.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 3 / 9

slide-76
SLIDE 76

If

If the expression evaluates as True, the statements of the body of the if are executed: if (condition){ statements; }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 4 / 9

slide-77
SLIDE 77

If-else

If the expression evaluates as True, the statements of the body of the if are executed, in other case the statements of the body of the else are exectuted. if (condition){ statements; } else { statements; } do signo.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 5 / 9

slide-78
SLIDE 78

If-else: style

Each block → one level of indentation. We can visually ignore details → legibility. The code is indented with the tab.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 6 / 9

slide-79
SLIDE 79

else if

Simplificates the program when there are multiple cases No new functionality, the same can be expressed with nested if-else. if (condition){ statements; }else if (condition) { statements; }else if (condition) { statements; }else{ statements; } change signo.p see notasimple.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 7 / 9

slide-80
SLIDE 80

case

Select based on an discrete types (int, char...). Can always be changed into a (longer) else if. All possible cases need to be covered , (comma) to express a discrete set of values. .. (dot dot) to express a range of ordinals.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 8 / 9

slide-81
SLIDE 81

case

switch(expresion){ case valx , valy , valn: statements; case val0: statements; case val0, val1 .. valn: statements; default: statements; } do fechavalida.p do sieteymedia.p do hexa2decimal.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 4: Selection Problems October 24, 2011 9 / 9

slide-82
SLIDE 82

Lecture 5: Variables and Procedures

Programming Fundamentals Gorka Guardiola

LS, GSYC, URJC

November 8, 2011

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 1 / 21

slide-83
SLIDE 83

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 2 / 21

slide-84
SLIDE 84

Variables

Object representing a piece of memory modifiable with an asociated identifier (name). It is of a concrete data type during its lifetime. Variables are declared inside the main program or in a subprogram. Variables have to be initialized (given a value) before being used.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 3 / 21

slide-85
SLIDE 85

Variables

procedure sum () /∗ d e c l a r a t i o n ∗/ number1 : int ; number2 : int ; r e s u l t : int ; { /∗ i n i t i a l i z a t i o n ∗/ number1 = 5; number2 = 6; /∗ use ∗/ r e s u l t = number1 + number2 ; w r i t e l n ( r e s u l t ) ; }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 4 / 21

slide-86
SLIDE 86

Declaration

A name is given to the variable. The name is an identifier. A space is reserved in memory, but without giving it any value. Names should be chosen:

◮ Short: more readable. ◮ Descriptive and clear: seeing the name should make the reader

understand what the variable stands for.

The shortest name that expresses what the variable is.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 5 / 21

slide-87
SLIDE 87

Declaration

Example: variable used to calculate the radius of a circle for a program calculating its area: procedure a r e a c i r c l e () r a d i u s o f t h e c i r c l e : f l o a t ; /∗ bad , too long ∗/ r a d i u s c i r c l e : f l o a t ; /∗ redundant ∗/ r a d i o : f l o a t ; /∗ ok ∗/ r : f l o a t ; /∗ ok , context i s important ∗/ a : f l o a t ; /∗ bad , not d e s c r i p t i v e ∗/ rdo : f l o a t ; /∗ bad , u n c l e a r ∗/ { . . . }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 6 / 21

slide-88
SLIDE 88

Assignment

Gives value to the value Different to an equation left: identifier of the variable right: expression, same type of the variable. Initialization: first assignment, first value Before initialization, value is unknown. We can assign as many times as we want. ntimes = 7; . . . ntimes = 42;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 7 / 21

slide-89
SLIDE 89

Use

Expressions can be used as we have been using literals. Variables can be passed as arguments to subprograms. ntimes = 7; ntimes = ntimes + 1; w r i t e l n ( ntimes ) ; f a c t o r i a l ( ntimes ) ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 8 / 21

slide-90
SLIDE 90

Visibility and scope

Scope of the variable: from the declaration to the end of the subprogram. Global variable: external to any subprogram. Local variable: declared inside a subprogram. Picky does not permit it but in any case, global variables, are a bad idea in a subprogram → use parameters.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 9 / 21

slide-91
SLIDE 91

Hiding

There could be different objects with the same identifier in nested scopes. If the identifier is used, it references the closest scope (inner). The concrete rules depend on the language. They may not even be the same data type, kind of object. Bad idea to hide identifiers, though Picky forbids it anyway.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 10 / 21

slide-92
SLIDE 92

Reading a value

We can read from the standard input: read. Like write is part of Picky. . . . number : int ; . . . w r i t e ( ” input a number : ” ) ; read ( number ) ; number = number + 1; w r i t e l n ( number ) ; see gets.p see leerhexa.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 11 / 21

slide-93
SLIDE 93

Until today...

We had functions and constants Functions without parameters → constants. Functions with parameters → mathematical function.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 12 / 21

slide-94
SLIDE 94

Functions

Need to preserve referential transparency. Lateral effect: any effect outside of the function Breaking referential transparency, a function is not a mathematical function any more, we need to worry about the state of the whole program. To differentiate when this is necessary (as little as possible) we use procedures.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 13 / 21

slide-95
SLIDE 95

Functions should not

should not read or write is a lateral effect should not modify the global state (global variables) should not modify parameters (in Picky, impossible, only ref parameters in procedures)

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 14 / 21

slide-96
SLIDE 96

Paradigms

Declaring and defining functions and constants. Preserving referential transparency: functional programming. Sequences of orders, lateral effects: imperative programming.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 15 / 21

slide-97
SLIDE 97

Procedures

We have already seen one, main. Declared and defined like functions but with procedure instead of function procedure p r i n t i n c r e m e n t (n : int ) { w r i t e l n (n + 1 ) ; }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 16 / 21

slide-98
SLIDE 98

Parameters

By value: The formal parameter (argument) is a copy of the real parameter (parameter) and is not copied back at the end of the procedure. Pass by reference: he formal parameter (argument) is the same as the real parameter (parameter) In Picky: ref name procedure increment ( r e f n : int ) { n = n + 1; } do incrementar.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 17 / 21

slide-99
SLIDE 99

Reference

By value: Important concept, another name for the same thing (argument vs. parameter) Modifying an argument passed by reference → lateral effect do incrementar.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 18 / 21

slide-100
SLIDE 100

Functions should not

should not read or write is a lateral effect should not modify the global state (global variables) should not modify parameters (in Picky, impossible, only ref parameters in procedures)

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 19 / 21

slide-101
SLIDE 101

rectangle.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 20 / 21

slide-102
SLIDE 102

Programs

Read a rectangle. Interchange two numbers (of two variables). Second degree equation solving. Dates.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 5: Variables and Procedures November 8, 2011 21 / 21

slide-103
SLIDE 103

Lecture 6: Scalar Types and Tuples

Programming Fundamentals Gorka Guardiola

LS, GSYC, URJC

November 7, 2011

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 1 / 12

slide-104
SLIDE 104

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 2 / 12

slide-105
SLIDE 105

Data Types

Data of a homogeneous type with associated operations. We had: int, float, char, boolean. We can define our own data types. Better having a data type than a thousand arguments. Better a data type than numbers. sieteymedia.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 3 / 12

slide-106
SLIDE 106

Enumerated types

Define a data type by enumerating the elements.

types : TypeCardValue = ( As , Dos , Tres , Cuatro , Cinco , Seis , Siete , Sota , Caballo , Rey ) ; TypeSuit = ( Oros , Copas , Espadas , Bastos ) ; . . . v a l u e : TypeCardValue ; s u i t : TypeSuit ; . . . v a l u e = As ; s u i t = Oros ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 4 / 12

slide-107
SLIDE 107

Enumerated types

We will name user defined types TypeFoo to distinguish them from variables, constants, etc. The names between parenthesis can be used as literals of that type. Identifiers have to be clear so that they are not confused with the names of other things. They start with upper case. Internally they are mapped to int.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 5 / 12

slide-108
SLIDE 108

Enumerated types

int, bool, and char are really enumerated types predefined in Picky! This kind of types are also called ordinals. We can compare them (like with char). We have some operations for all of them:

◮ pred(elem): element before this one (predecessor). ◮ succ(elem): next element (successor). ◮ int(elemento): int associated to an element ◮ element(int): element associated to an int.

sieteymedia2.p dias.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 6 / 12

slide-109
SLIDE 109

Predefined constants

Maxint Minint biggest and smallest integer. Maxchar Minchar biggest and smallest char. Nothing similar for other enumerated (I know the last).

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 7 / 12

slide-110
SLIDE 110

Subranges

They are new types, defined as a limit in range from other types. It does not really introduce a new type (be careful) it is subset of the

  • riginal type they come from and thus, compatible.

They are defined with ranges (we already know them from case).

types : TypeWeekday = (Mon, Tue , Wed, Thu , Fri , Sat , Sun ) ; TypeWorkday = TypeWeekday Mon . . F r i ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 8 / 12

slide-111
SLIDE 111

Tuples

Idea: create a new type composed of various elements of different types. The new type is the cartesian product: the set of all possible ordered tuples with all the possible elements on each possition. In Picky we represent this as (records). Each position of the tuple in a record is called field.

types : TypeCoordinate = r e c o r d { x : i n t ; y : char ; };

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 9 / 12

slide-112
SLIDE 112

Record

Fields are accessed with a dot.

coor : TypeCoordinate ; . . . coor . x = 33; coor . y = ’ a ’ ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 10 / 12

slide-113
SLIDE 113

Records

Can be used as parameters to a subprogram. Can be assigned directly. Can be compared for equality/inequality == or ! =. The other comparison operators cannot be used. Cannot be read or written (read, write) directly. They must be read or written field by field. A field of a record may be another record. Literals for records (i.e. definition of constants), are expressed as aggregates:

c o n s t s : CoorZero = TypeCoordinate (0 , ’ a ’ ) ;

ver sieteymedia3.p ver eq2grado2.p ver manejarectangulo2.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 11 / 12

slide-114
SLIDE 114

Abstraction

Records let us abstract the data we use to organize it. They are data structures. Subprograms let us abstract subproblems and the algorithms to solve them. To write programs it is necessary to abstract and ignore details. ALGORITHMS + DATA STRUCTURES = PROGRAMS

Gorka Guardiola (LS, GSYC, URJC ) Lecture 6: Scalar Types and Tuples November 7, 2011 12 / 12

slide-115
SLIDE 115

Lecture 7: Loops

Programming Fundamentals Gorka Guardiola

LSUB, GSYC, URJC

November 28, 2011

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 1 / 12

slide-116
SLIDE 116

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 2 / 12

slide-117
SLIDE 117

Loops

Control structure to repeat the execution of a block of statements a number of times. Questions:

◮ Is the execution going to enter the loop? ◮ What will be done on each execution?

Pay special to the first and last iteration.

◮ When do we exit the loop?

NB: There are infinite loops. ver tabladel7.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 3 / 12

slide-118
SLIDE 118

Repeat while

The loop will continue iterating if the condition is true.

while ( c o n d i t i o n ){ . . . }

sieteymedia4.p contarhasta.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 4 / 12

slide-119
SLIDE 119

Do while

The condition to exit is checked at the end of the loop. The block is executed at least once. This loops are known as do-while.

do{ . . . } while ( c o n d i t i o n ) ;

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 5 / 12

slide-120
SLIDE 120

When we know the number of iterations

There is a control variable used to control the iteration. On each iteration the control variable has a value in the range defined by the loop. The variable must have beend declared before and has to be of an

  • rdinal type (pred will be used to go down and succ to go up).

It cannot be modified inside the loop (it is a bad idea, because it is used to control the iteration. The for header consists of two parts, an initialization and a comparison. The loop iterates until the comparison is not true.

f o r ( i = 1 , i < 10){ . . . }

hacer diezdesde.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 6 / 12

slide-121
SLIDE 121

for

If the comparison is lower or lower than, the loop goes down using pred.

f o r ( i = 5 , i >= 1){ . . . }

hacer cuentaatras.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 7 / 12

slide-122
SLIDE 122

for

for can be used with enumerates.

f o r ( day = Thu , day >= Lun ){ . . . }

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 8 / 12

slide-123
SLIDE 123

Nested loops

To loop over multidimensional objects When we need to repeat an operation several times per element in a collection. For example:

while ( c o n d i c i o n ){ f o r ( i = 1 , i <= 5){ . . . } }

ver imprimirbajara.p ver figuras.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 9 / 12

slide-124
SLIDE 124

When should we use each time of loop?

while: when the number of iterations is unknown and we may not need to enter the loop at all. loop-exit-when: when the number of iterations is unknown and we need to enter the loop at least once. for: when the number of iterations is known. Advantage: avoid getting into an infinite loop by accident.

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 10 / 12

slide-125
SLIDE 125

Efficiency

It is difficult to know how long it will take to run a program. If we iterate through whole collections without the need, it will take more. If we have nested loops (quadratic complexity if nested once, count the number of steps) it will take more than if we don’t. arreglar esprimo.p

Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 11 / 12

slide-126
SLIDE 126

What matters?

From highest to slowest priority:

1 Correctness and legibility 2 Speed 3 Waste of memory Gorka Guardiola (LSUB, GSYC, URJC ) Lecture 7: Loops November 28, 2011 12 / 12

slide-127
SLIDE 127

Lecture 8: Collections

Programming Fundamentals Gorka Guardiola

LS, GSYC, URJC

January 10, 2012

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 1 / 20

slide-128
SLIDE 128

Lecture 8: Collections

Programming Fundamentals Gorka Guardiola

LS, GSYC, URJC

January 10, 2012

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 2 / 20

slide-129
SLIDE 129

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 3 / 20

slide-130
SLIDE 130

Arrays

Ordered collection of elements of the same type. Each element has a position, a corresponding enumerated (index). They are also know as vectors o indexed collections. Important: not to be confused with registers.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 4 / 20

slide-131
SLIDE 131

Arrays

Define the type and number of elements in the declaration. Each element is like a variable of that type. Elements are one after the other in memory. Arrays of different size are of different type (in Picky).

types : TypePrimeList = a r r a y [ 0 . . 9 ]

  • f

i n t ; TypeMusHand = a r r a y [ 0 . . 4 ]

  • f

TypeCard ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 5 / 20

slide-132
SLIDE 132

Arrays, ideas

Constant for the maximum element Define a subrange for the array

c o n s t s : NumMaxAlumn = 60; types : TypeRangeAlumnList = i n t 0 . . NumMaxAlumn−1; type TypeAlumnList = a r r a y [ TypeRangeAlumnList ]

  • f

TypeCard ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 6 / 20

slide-133
SLIDE 133

Arrays

Elements are accessed by index.

types : TypeMusHand = a r r a y [ 0 . . 4 ]

  • f

TypeCard ; . . . hand : TypeMusHand ; { hand [ 0 ] = TypeCard ( As , Oros ) ; hand [ 1 ] = TypeCard ( Rey , Copas ) ; hand [ 2 ] = TypeCard ( Sota , Bastos ) ; hand [ 3 ] = TypeCard ( Caballo , Bastos ) ; hand [ 4 ] = TypeCard ( Sota , Bastos ) ; }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 7 / 20

slide-134
SLIDE 134

Arrays

The range can be any enumerated type.

types : TypeUrban = ( Hamlet , V i l l a g e , Town , City ) ; TypeUrbanBus = a r r a y [ Hamlet . . City ]

  • f

i n t ; . . . buses : TypeUrbanBus ; . . . buses [ Hamlet ] = 3; . . . w r i t e ( ”The maximum number

  • f

buses f o r a hamlet i s : ” ) ; w r i t e l n ( buses [ Hamlet ] ) ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 8 / 20

slide-135
SLIDE 135

Arrays

To iterate over an array loops are used.

f o r ( p o p u l a t i o n = Hamlet ; p o p u l a t i o n <= City ){ w r i t e ( buses [ p o p u l a t i o n ] ) ; }

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 9 / 20

slide-136
SLIDE 136

Arrays

Arrays can be initialized directly with an aggregate.

types : TypeUrban = ( Hamlet , V i l l a g e , Town , City ) ; TypeUrbanBus = a r r a y [ Hamlet . . City ]

  • f

i n t ; . . . buses : TypeUrbanBus ; . . . buses = TypeUrbanBus (1 , 10 , 100 , 2000);

ver ciudades.p hacer listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 10 / 20

slide-137
SLIDE 137

Arrays

Arrays of the same type, remember, same type of elements, same size: Can be assigned. Can be compared ( == and != ). NB: All the elements are compared

/∗ l i s t 1 l i s t 2 and l i s t 3

  • f

the same type ∗/ l i s t 1 = l i s t 2 ; a r e e q u a l = l i s t 1 == l i s t 3 ;

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 11 / 20

slide-138
SLIDE 138

Programming problems

Direct solution problems. √ Selection problems. √ Problems with data collections. ←

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 12 / 20

slide-139
SLIDE 139

Problems with data collections

Accumulate. Search. Maximize/minimize. Construct. If you master this four types, you master all of them.

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 13 / 20

slide-140
SLIDE 140

Accumulate

Iterate over the collection accumulating values to calculate something. Example: calculate the average grade for a course. ver listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 14 / 20

slide-141
SLIDE 141

Search

Iterate over the collection searching for an element. Example: search for the student with record number 324. ver listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 15 / 20

slide-142
SLIDE 142

Maximize/minimize

Iterate over the collection searching for a maximum or a minimum. Example: search for the student with highest grade. ver listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 16 / 20

slide-143
SLIDE 143

Construct

Build an object from the collection. Example: order a list of students by their record number. ver listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 17 / 20

slide-144
SLIDE 144

Example: order

Paso 4 Paso 3 Paso 2 Paso 1 2 3 5 2 6 2 2 5 3 6 3 2 5 2 6 2 3 5 2 6 2 2 5 3 6 2 2 3 5 6 2 2 3 5 6 2 2 3 5 6

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 18 / 20

slide-145
SLIDE 145

Character strings: String

Very common data type, not special in Picky. Array of char with index starting in 0. Special aggregate for strings with “ Same operators as any other array Remember, size is part of the type ver capitaliza.p ver palindromo.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 19 / 20

slide-146
SLIDE 146

String Aggregates

Strings can be initialized directly with an aggregate. Take in account that the size is part of the type

types : TypeRangeAlumnName = i n t 0 . . NumMaxAlumn−1; TypeAlumnName = a r r a y [ NumMaxAlumn ]

  • f

i n t ; c o n s t s : AnonName = ”Anonymous . . . . ” ; . . . alumn : TypeAlumnName ; . . . alumn = ”Pepe Gonzalez ” ; . . . alumn = AnonName ;

ver ciudades.p hacer listaalumnos.p

Gorka Guardiola (LS, GSYC, URJC ) Lecture 8: Collections January 10, 2012 20 / 20

slide-147
SLIDE 147

Lecture 9: Files

Programming Fundamentals Gorka Guardiola

LSUB, GSYC, URJC

10 de enero de 2012

slide-148
SLIDE 148

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

slide-149
SLIDE 149

Files

  • Persistent data collections.
  • Maintained by the operating system. Picky only provides

access.

  • We will only see text files.
slide-150
SLIDE 150

Working with files

1 Open the file 2 Read and/or write into the file. 3 Close the file.

slide-151
SLIDE 151

Open the file

  • To open the file, there is a procedure open with three

parameters:

1 Picky’s representation of a file, a reference to a variable of

type file.

2 The name of the file to open, a string. 3 Open mode, which is a string:

  • “r”: to read.
  • “w” to write, truncates (empties) the file.
  • “rw” to read and write.
slide-152
SLIDE 152

Standard input and standard output

  • Where the programs read and write normally.
  • Already opened.
  • Normally, the keyboard and the screen (though not always).
  • stdin: predefined variable of type file representing the

standard input.

  • stdout: predefined variable of type file representing the

standard output.

slide-153
SLIDE 153

Close a file

  • General rule:

We have to free the resources we have allocated when we do not need any more.

  • After working with a file, the file needs to be closed to free

the resources needed to keep the file open.

  • The close procuder closes the file.
  • The only argument is a reference to a file of type file.
  • The standard input and ouput do not need to be closed.
slide-154
SLIDE 154

read and write

  • We have already been reading and writing!
  • We already know: read, write, writeln and writeeol.
  • There is a version of those procedures to work with other files.
  • The name of the procedures starts with an “f” and there is an

extra first argument, the file variable.

m y f i l e : f i l e ; l e t t e r : char ; . . .

  • pen ( myfile ,

” b l a b l a . t x t ” , ” r ” ) ; f r e a d ( myfile , l e t t e r ) ; c l o s e ( m y f i l e ) ;

leern.p

slide-155
SLIDE 155

Sequential access

  • An open file has an associated offset specifying the position

where it will read or write (the offset).

  • After opening the file the position is 0, the first character.
  • The access is sequential.
  • Each time you read or write, the offset moves forward.
slide-156
SLIDE 156

Lines

  • Text files have an end of line at the end of each line.
  • The end of line is represented by the constant Eol. On each

system it is different and can be formed by one or more characters.

  • It is special, so to write Eol, we must call writeeol.
  • End of file is represented in Picky with a constant Eof. Eof is

just a condition, not represented by charactes inside the file. Eol and Eof have to be dealt with specially

slide-157
SLIDE 157

What read sees

H

  • l

a

  • a

m i g

  • ,

EOL a

Hola amigo, adios.

d i

  • s

. EOL EOF

slide-158
SLIDE 158

Reading strings: read

  • If we pass a string as a parameter, read reads characters

filling the length of the string.

  • If there is an Eol in the middle: it fails.
  • If we get an Eof: it fails.
  • Not possible to read in a controlled way!.

ver leerstring.p

slide-159
SLIDE 159

Reading int and float

  • read skips white spaces, tabs and Eol previous to the

element.

  • If the first character cannot be in a number of it is Eol, it

fails!.

  • Read all the characters forming the number and converts it to

the numerical data type of the variable being read.

  • Can fail if the number is not well defined!
slide-160
SLIDE 160

Controlled reading

  • The function eol (and feol) tells us if the last read found
  • Eol. In that case we have to skip it. (undefined if there has

been no read yet)

  • The procedure readeol (and freadeol) skips the Eol.
  • The function eof (and feof) tells us if the last read found
  • Eof. In that case we cannot read again.
slide-161
SLIDE 161

Controlled reading

  • The procedure peek (and fpeek) tells us what the next

character in the file will be. In receives a char variable by reference.

1 If we are at the end of line, we will get an Eol. 2 If there are no more characters, the char will be Eof (if we

have already seen Eof, there will be an execution error.

leerlineas.p pangrama.p cuentapalabras.p

slide-162
SLIDE 162

Lecture 10: Pointers

Programming Fundamentals Gorka Guardiola

LSUB, GSYC, URJC

10 de enero de 2012

slide-163
SLIDE 163

(cc) 2010 Grupo de Sistemas y Comunicaciones. Some rights reserved. This work is provided under Creative Commons Attribution License - NonCommercial - NoDerivs (by-nc-nd). To obtain the complete license go to http://creativecommons.org/licenses/by-sa/2.1/es. or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

slide-164
SLIDE 164

Until now

... a variable could be:

  • Global or static: “lives” for the whole execution
  • Local or automatic: “lives” during a call of a subprogram it is

created and destroyed.

slide-165
SLIDE 165

Problems

We have to know before running the program the size of an object:

  • We cannot go further than the mamimum size (array).
  • We can declare a big size but then we waste memory.
  • During the execution, you cannot create new variables that

“survive” the subprogram (local variables also called automatic variables are destroyed on return).

slide-166
SLIDE 166

Dynamic variables

  • Can be created and destroyed while executing.
  • Creation is called dynamic memory allocation.
  • Destruction is called dynamic memory freeing.
slide-167
SLIDE 167

Dynamic variables

  • They are variables that are created while the program is

running.

  • They have no name (you cannot give them one)
  • Then... how do we access them? → pointers.
slide-168
SLIDE 168

Pointers

  • A pointer is a variable that contains a memory address.
  • It can be seen as a variable containing an arrow (to point),

but do not lose sight of what it is.

  • A pointer points to a variable of a data type.

Example: a pointer to int points to an int, cannot point to another data type, (char, float, TypeColor, etc.).

slide-169
SLIDE 169

Pointers

  • Define their data types as TypePtr in order not to get

confused to the type they point to.

  • An uninitialized pointers points to? (remember: variables need

to be initialized).

types : TypePtrEntero = ˆ i n t ; TypePtrChar = ˆ char ; TypePtrCarta = ˆ TypeCarta ; . . . pent : TypePtrEntero ; /∗ d e c l a r a t i o n

  • f

a p o i n t e r v a r i a b l e ∗/ pchar : TypePtrChar ; /∗ d e c l a r a t i o n

  • f

a p o i n t e r v a r i a b l e ∗/

slide-170
SLIDE 170

NB: To simplify the diagrams, all the data types are drawn as one byte.

pent pchar

???

???

pent pchar

0x40 0x41

???

0x42 0x43 0x44 0x59 0x60 0x61 0x80 0x81 0x82

... ...

??? EN MEMORIA:

0x00

...

¡Basura!

slide-171
SLIDE 171

Pointers

  • To initialize a pointer to point to nowhere use nil.
  • nil means nowhere (but is a real value).

. . . pent = n i l ; pchar = n i l ; . . .

slide-172
SLIDE 172

pent pchar

NIL

pent pchar

0x40 0x41 NIL 0x42 0x43 0x44 0x59 0x60 0x61 0x80 0x81 0x82

... ...

EN MEMORIA:

0x00

...

slide-173
SLIDE 173

Pointers

  • “Create” a new dynamic variable with new.
  • It is allocated, during the execution in a new piece of memory.

. . . new ( pent ) ; new ( pchar ) ; . . .

slide-174
SLIDE 174

pent pchar

???

0x60

pent pchar

0x40 0x41 0x80 0x42 0x43 0x44 0x59 0x60 0x61 0x80 0x81 0x82

... ...

??? EN MEMORIA:

0x00

...

??? ???

reservada reservada

¡Basura!

slide-175
SLIDE 175

Pointers

  • To access to the pointed value, use ^.
  • This is called apply an indirection, or crossing the pointer.
  • Crossing a pointer with value nil crashes the program (fatal

error).

  • Crossing an uninitialized pointer produces a random error.

. . . pent ˆ = 8 ; pchar ˆ = ’X ’ ; . . .

slide-176
SLIDE 176

pent pchar

8

0x60

pent pchar

0x40 0x41 0x80 0x42 0x43 0x44 0x59 0x60 0x61 0x80 0x81 0x82

... ...

'X' EN MEMORIA:

0x00

...

8 'X'

reservada reservada

slide-177
SLIDE 177

Pointers

  • When a variable is no longer in use, it must be freed.
  • For that there is a procedure: dispose.
slide-178
SLIDE 178

Pointers

  • After freeing it is useful to set the pointer to nil.
  • Crossing a pointer with freed memory will give an error.
  • In Picky it gives back an execution error.
  • In other languages, it creates a poltergeist,, very difficult to

debug.

. . . d i s p o s e ( pent ) ; pent = n i l ; d i s p o s e ( pchar ) ; pchar = n i l ; . . .

slide-179
SLIDE 179

pent pchar

NIL

pent pchar

0x40 0x41 NIL 0x42 0x43 0x44 0x59 0x60 0x61 0x80 0x81 0x82

... ...

EN MEMORIA:

0x00

...

slide-180
SLIDE 180

Dynamic memory

  • Everything allocated needs to be freed when no longer

used

  • If our program ends and we have not freed everything, we

have an error. This is a leak.

  • Some programming languages free automatically their

memory, garbage collection, others don’t. Picky does not. punteros0.p punteros1.p

slide-181
SLIDE 181

Linked list

  • A list (chain really) of registers (links) of undefined legth.
  • They are composed by dynamic variables linked one after

another by a pointer.

  • Very used in all kinds of programs.
slide-182
SLIDE 182

Linked list

  • Node: a record with a field which is a pointer to a record of

the same kind.

  • A node points the the next node.
  • The last node points to nil.
  • A new node can be added to the list on one end.
  • List: a record with a pointer to the first node and maybe

another to the last node. If empty, points to nil.

slide-183
SLIDE 183

Linked list

nil nil primero ultimo

slide-184
SLIDE 184

Linked list

nil primero ultimo sig

slide-185
SLIDE 185

Linked list

primero ultimo nil sig sig

slide-186
SLIDE 186

Linked list

primero ultimo nil sig sig sig

slide-187
SLIDE 187

Linked list

primero ultimo nil sig sig sig sig

slide-188
SLIDE 188

Different kinds

  • With one pointer.
  • Insert in the head.
  • Doubly linked.
  • Queues.
  • Stacks.
  • ...

ver listapalabras.p