week 5 control structures for programming: selection ... · pdf filecontrol structures for...

61
ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 1 Week 5 Control Structures for Programming: Selection, Functions ENGG1811 Computing for Engineers

Upload: lyhanh

Post on 10-Mar-2018

248 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 1

Week 5 Control Structures for Programming: Selection, Functions

ENGG1811 Computing for Engineers

Page 2: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 2

The Story So Far

You should have some understanding of

•  Subprogram structure Sub  Foo()  ...  End  Sub  •  Variable declarations Dim  myvar  As  Double  •  Types Double, also Long,  Boolean,  String

•  Assignment statements myVar  =  -­‐1  

•  Arithmetic expressions: myVar  =  2*yourVar  +  herVar/3.5  –  1.6  

•  Mod and \ operators

•  Running programs from the editor and menus

•  Displaying results: MsgBox  "Result  is  "  &  myVar    

Page 3: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Examples of control

If too hot increase cold air flow

Otherwise too cold decrease cold air flow

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 3

If frontal collision detected trigger the air bag

Control is used extensively in computer programs: •  Vehicle stability

control •  Precision

manufacturing •  Chemical process

control •  and more

Modern luxury vehicles contain many computer programs (about 100 million lines of code) http://spectrum.ieee.org/green-tech/advanced-cars/this-car-runs-on-code

Page 4: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Fault tolerant control

•  Example: How to keep the flight going when the plane has experience severe damages?

•  Automatic fault diagnosis and control

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 4

Damage 1

Damage 2

Normal

Damage n

Normal control

Algorithm 1

Algorithm 2

V . Flight Test Result s wit h St at e Dependent Guidance and Baseline L inearCont rol ler

A . A symmet r ic St r uct ural Damage: 50% r ight wing fai lur e

Wepresent ! ight test results as theaircraft undergoesa 50% right wing loss (along with losing complete rightaileron funct ionality) in autonomous ! ight with thebaselinenon-adapt ive controller and the state-dependentadapt ive guidance logic. The results indicate that the aircraft is able to maintain autonomous ! ight in spiteof the severe st ructural damage. Figure 3 shows the GT Twinstar in autonomous ! ight with 50% rightwing loss. Figure 4 show the ground track of the aircraft as the aircraft performs a holding pat tern abouta given waypoint , aircraft jet t isons 50% right wing at 2021 seconds into ! ight . Figure 5 shows the recordedalt itude of the aircraft . Figure 6 shows the recorded angular rates, it can be seen that while the aircraft issuccessful in maintaining ! ight , the angular rate has some oscillat ion. Part icularly, oscillat ions in angle ofat tack and roll are observed, which result in oscillat ions in alt itude seen in Figure 5. Figure 7 shows therecorded control inputs, it can be seen that the rudder, aileron, and throt t le often saturate, part icularly, theaileron saturat ing at its minimum value repet it ively as the aircraft t ries to maintain level ! ight . Adapt ivecont rol algorithms are current ly being tested that augment the baseline cont rol algorithm to mit igate theobserved oscillat ions and enable safe landing in presence of signi�cant st ructural faults.

F igure 3. G T T winstar in autonomous ! ight aft er jet t isoning 50% right wing.

B . Fai lure of al l aerodynamic e�ect or s: Propulsion only cont r ol

Thepresented algorithm isable to mit igate thecomplete lossof all aerodynamic e�ectorsby using di�erent ialthrot t le for cont rol. This ! ight condit ion is termed as Propulsion only cont rol. Figure 8 shows the groundtrack of the Twinstar UAS as it t racks an ellipt ical pat tern in propulsion only cont rol, while Figure 9shows the alt itude. Figure 10 shows the control commands. At around 1055 seconds into ! ight , the loss ofaileron, elevator, and rudder actuators is simulated by keeping them constant ; the control from this pointonward is accomplished by using only di�erent ial throt t le. The last sub�gure in Figure 10 shows that thedi�erent ial throt t le only gets act ivated when the aerodynamic e�ectors are deemed failed. Figure 11 showsthe angular rate data. Despite increased oscillat ions in roll, the control performance of the UAS was foundto be sat isfactory to enable landing.

6 of 18

American Inst it ute of Aeronaut ics and Ast ronaut ics

Dow

nloa

ded

by U

NIV

ERSI

TY O

F N

EW S

OU

TH W

ALE

S on

Aug

ust 1

3, 2

014

| http

://ar

c.ai

aa.o

rg |

DO

I: 10

.251

4/6.

2011

-142

8

Chowdhary et al. Autonomous Guidance and Control of Airplanes under Severe Damage, 2011

Algorithm n

Page 5: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 5

Program State

•  The program state is the set of active variables and objects, external device state plus current execution position

•  Control structures let the programmer cause actions to occur (or recur) based on decisions about the program state

•  Main control structures are –  procedures (for grouping subtasks) –  selection (do something or perhaps do something else) –  iteration (do something as long as required)

Page 6: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 6

Boolean Expressions

•  All decisions are represented by Boolean expressions

•  Boolean expressions evaluate to True or False  •  Involve relational operators to compare values

•  Examples: 2  <  3    num1  >=  num2          intSum  <>  0  strName  <=  "Zanzibar"              '  string  comparison  Now()  >  "2014-­‐08-­‐25"            '  date  comparison  j  =  3    strID  =  "A400“  

•  context determines whether the last two are relational (comparison) expressions or assignment statements. We will use the sub-program DemoBoolean() to understand this.

Basic: = <> < <= >   >=  

Maths: = ≠ < ≤ > ≥

Page 7: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

DemoBoolean() •  We will also use this program to illustrate how to use break point

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 7

Click in the margin to set a break point

Page 8: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

•  Symmetric form: If boolean-expression Then

statement-list1 Else  

statement-list2

End  If  

•  boolean-expression is evaluated –  If it evaluates to True, statement-list1 is executed

–  Otherwise, statement-list2 is executed

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 8

Selection If/Then/Else  

indented!

indented!

always on a new line

flowchart

boolexpr

stmts1

False True

stmts2

Page 9: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

•  The If/Then statement is used to make decisions using Boolean expressions

•  Simplest form:

If boolean-expression Then statements

End  If  

•  boolean-expression is evaluated –  If it evaluates to True, statements are executed

–  otherwise (i.e., it must be False) skip over statements and continue with rest of program

•  Also referred to as a conditional statement

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 9

Selection – If/Then  

indented!

flowchart

boolexpr

statements

False

True

Page 10: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Absolute value

•  We will show two implementations of computing the absolute value, using –  If/Then/Else –  If/Then

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 10

|x| =⇢

x if x � 0

�x otherwise

Page 11: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 11

Absolute  value:  If/Then/Else example

If  intVal  >=  0  Then          intAbsVal  =  intVal  Else          intAbsVal  =  -­‐intVal      '  unary  minus*  End  If    '  *  much  preferred  to  these  change-­‐sign  equivalents:      intVal  =  intVal  *  -­‐1    '  yuk!      intVal  =  0  –  intVal      '  double  yuk!  

indented!

Code in Abs1

Page 12: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 12

If/Then example

intAbsVal  =  intVal  If  intAbsVal  <  0  Then          intAbsVal  =  -­‐intAbsVal      '  unary  minus*  End  If  '  now  we  know  that  intAbsVal  =  |intVal|  '  regardless  of  whether  intVal  is  positive  or  negative    

indented!

Code in Abs2

Page 13: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 13

Examples

'  Larger  value    '  s  =  sign  of  a  (+1,-­‐1,0)  If  a  >  b  Then      If  a  <>  0  Then          max  =  a        If  a  >  0  Then  Else              s  =  1          max  =  b        Else    '  a  <  0*  End  If            s  =  -­‐1                End  If              Else                  s  =  0              End  If            '  (chained  form  left  as  exercise)            '  *  justified  a  few  slides  later  

Code in MaxOf

Page 14: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 14

More complex form

Chained form, symmetric form generalised to n: If boolean-expression1 Then

statement-list1 ElseIf boolean-expression2 Then  

statement-list2

ElseIf boolean-expression3 Then  

statement-list3 … Else  

statement-list-n

End  If  Mantra: indent all statement lists embedded in a selection statement

Single keyword ElseIf,

not two words

Page 15: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 15

Chained Selection example: Classification

Often need to classify a value based on ranges, such as deriving UNSW grade from mark (excluding PC):

'  Precondition  (assumption):  0  <=  mark  <=  100  If  mark  >=  85  Then          grade  =  "HD"  ElseIf  mark  >=  75  Then      '  And  Not  (mark  >=  85)          grade  =  "DN"  ElseIf  mark  >=  65  Then          grade  =  "CR"  ElseIf  mark  >=  50  Then          grade  =  "PS"  Else                        '  Not  (mark  >=  50),  so  mark  <  50          grade  =  "FL"  End  If  

Code in Grade

Page 16: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 16

Chained Selection example: Classification

Often need to classify a value based on ranges, such as deriving UNSW grade from mark (excluding PC):

If  mark  >=  85  Then          grade  =  "HD"  ElseIf  mark  >=  75  Then        grade  =  "DN"  

ElseIf  mark  >=  65  Then          grade  =  "CR"  ElseIf  mark  >=  50  Then          grade  =  "PS"  Else                                  grade  =  "FL"  End  If  

Explaining the principle: A mark may satisfy multiple conditions. Only the statement associated with the first satisfied condition is executed. Example: A mark of 76 satisfies: •  mark >= 75 •  mark >= 65 •  …

“mark >= 75” is the first satisfied clause, so ONLY execute grade = “DN”

Page 17: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 17

Classification order When chained selection is used to identify which range a value lies in, the best strategy is always to start from the highest (or lowest) threshold and work progressively to the other end

•  n possible ranges have n–1 boundaries •  each boundary value is mentioned once only •  UNSWgrade is exactly like this (5 grades, 4 comparisons)

b1 b2 b3

< b1 b1 to b2 b2 to b3 ≥ b3

Each decision divides the space into two parts

The module GradeMU demonstrates what can go wrong. Beware: GradeMU contains errors.

Page 18: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 18

Boolean Expressions

Boolean expressions comprise •  Boolean constants True    False  

•  Boolean variables

•  Relational operations (comparisons giving Boolean values)

•  Boolean operators binary And    Or    Xor  

unary Not  

Page 19: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 19

Truth Tables

Truth tables establish meaning of operators by enumerating each combination of operands and showing what the operation yields

Notation: T = True, F = False A B A And B A Or B A Xor B Not A

F F F F F T F T F T T T

T F F T T F

T T T T F F

And – both True Or – either True Xor – either (but not both) True Not – complement

Page 20: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 20

Examples

x  >=  0.0  And  x  <  1.0    '  x  lies  between  0  (inclusive)                '              and    1  (exclusive)  

 a  =  b  And  b  =  c      '  all  three  are  the  same    j  <  0  Or  j  >  0      '  equivalent  to  ????    x  >=  0.0  Or  x  <  1.0    '  True  (why?)    Not  (y  >=  0)        ‘  equivalent  to  ????      Not  found        '  complement  of  variable  found  =  True      '  redundant,  just  use  found    Not  (E1  And  E2)      '  (Not  E1)  Or  (Not  E2)  Not  (E1  Or  E2)      '  (Not  E1)  And  (Not  E2)                '  =>  de  Morgan's  Laws  

Page 21: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

De Morgan’s Law example

•  P = Pressure, T = temperature

•  E1: P ≥ 300 •  E2: T ≥ 200

•  Plant is safe if neither pressure exceeds 300 nor temperature exceeds 200

•  Plant is safe if NOT (E1 or E2)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 21

Page 22: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

De Morgan’s Law example

•  E1: P ≥ 300 •  E2: T ≥ 200 •  Plant is safe if NOT (E1 or E2)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 22

NOT E1

T

200

300

P

T

200

300 P

T

200

300

P

E1 E2

NOT E2

E1 or E2

NOT (E1 or E2)

OR is the same as union

Page 23: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

De Morgan’s Law example

•  E1: P ≥ 300 •  E2: T ≥ 200 •  Plant is safe if NOT (E1 or E2) •  NOT (E1 or E2) = (NOT E1) AND (NOT E2)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 23

NOT E1

T

200

300

P

T

200

300 P

T

200

300

P

E1 E2

NOT E2

(NOT E1) and (NOT E2)

AND is the same as intersection

Code in DeMorgan

Page 24: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 24

Boolean Reasoning

If  a  <>  0  Then      If  a  >  0  Then        s  =  1      Else    '  a  <  0  *        s  =  -­‐1   …

Recall the sgn a example:

How did we know that a  <  0  at the point shown? •  We’ve passed the first condition, so a  <>  0  •  But we’ve failed the second condition, so Not  (a  >  0)  Hence we have a  <>  0  And  Not  (a  >  0)     =  a  <>  0  And  a  <=  0      '  by  definition  of  Not    =  a  <  0              '  by  definition  of  <>  and  <=  

Page 25: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Exercise: Leap year •  Leap year

–  A leap year must be divisible by 4 –  But not all centuries are leap years –  Centuries are leap years only if they are divisible by

400 •  2000, 2400 are leap years •  2100, 2200, 2300 are NOT leap year

•  You want to write a program to classify whether a given year is a leap year

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 25

year  =  2000  If  Boolean-­‐expression  Then      MsgBox  “Yes,  a  leap  year”  

Else      MsgBox  “No,  not  a  leap  year”  

End  If  

Can you come out with the Boolean expression?

You may need AND,

OR, NOT.

Page 26: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

A pictorial depiction

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 26

Leap years

All years

Mod 4 = 0

Centuries

Mod 400 = 0

2004 2100

2000

(year  Mod  4  =  0)  is  True  if  year  is  divisible  by  4,  otherwise  False  

The  following  test  whether  the  variable  year is divisible by 4:

Page 27: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

One possible answer

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 27

Leap years

All years

Mod 4 = 0

Centuries

2004 2100

2000

(year mod 400 = 0)

year divisible by 4 but not 100

OR

Page 28: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

One possible answer

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 28

Leap years

All years

Mod 4 = 0

Centuries

Mod 400 = 0

2004 2100

2000

(year mod 400 = 0)

(year mod 4 = 0 AND NOT (year mod 100 = 0))

OR

Question: Say, you’ve written the program and want to test it. What years should you use to test the program?

Page 29: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 29

Functions

•  Functions are procedures (named groups of statements) that evaluate and return a single value of a specified type (subprograms perform actions but don't return

anything) •  OO Basic functions can be used in formulas in sheet

cells, or called from other parts of a program •  Declaration is always

Function  name(parameters…)  As  type        declarations  for  local  variables        …  

     statements,  including  somewhere…  

     name  =  expression      End  Function  

(examples will be provided)

Assign expression of the right type to the function name to return answer

Page 30: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 30

Parameters

•  Values are passed to a function (or subprogram) via parameters

•  Look like variable declarations (and are) •  Corresponding values in call: arguments

Module1

Function  bigger(v1  As  Double,  v2  As  Double)  As  Double          If  v1  >=  v2  Then                  bigger  =  v1          Else                  bigger  =  v2          End  If  End  Function  

1. formula uses Basic function

2. values copied to parameters v1 and v2

5. result copied to cell containing

formula

3. function begins execution

4. return value assigned to

function name

Start here and follow

the numbers

Code in Bigger

Page 31: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 31

Built-in Functions

•  OO Basic includes a range of mathematical, string and other functions

•  Mathematical functions include –  Sin, Cos, Tan, Atn (arctangent), all in radians –  Abs, Sgn, Int (largest int ≤), Fix (truncate towards 0), Round (to any number of decimal places, including neg)

–  Sqr (√), Exp (e x), Log (ln x) –  Rnd (pseudo-random number)

•  Other functions –  IsNumeric(var) returns True if var is a number or can be

converted to a number, otherwise False –  Now()  returns the current time as a date value –  Format, allows numeric and other values to be formatted

according to a pattern

Page 32: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 32

Built-in Functions, continued

•  Can also use functions used in worksheet formulas, with the notation WorksheetFunction.name(args…)  

•  Examples: angle  =  WorksheetFunction.Radians(-­‐90)    angle  =  WorksheetFunction.atan2(x,  y)      '  returns  arctangent  of  y/x  in  the  correct      '  quadrant,  OK  even  if  x=0  

 payment  =  WorksheetFunction.PMT(rate,  _          numPeriods,  curValue)

Requires Option VBASupport 1 at the top of the module

Also works with cell values and ranges (next week)

Page 33: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 33

UNSW Grade Function

•  Embed algorithm (earlier slide) in function

•  One parameter, mark (type is Integer), returns String  

•  Use on worksheet, fill down formula

•  What if mark is out of range? Or not a number? (complete solution must

cover all cases, Variant type enables this)

Page 34: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 34

UNSWgrade with error checks Function  UNSWgrade(mark  As  Variant)  As  String  

If  Not  IsNumeric(mark)  Then    UNSWgrade  =  "Not  a  mark"    Exit  Function  

End  If    If  mark  <  0  Or  Mark  >  100  Then    UNSWgrade  =  "Mark  out  of  range"    Exit  Function  

End  If  

     algorithm  coded  as  before,  can  rely  on  valid  mark  range;      change  variable  name  grade  to  function  name  UNSWgrade  

End  Function  

Note early return after detecting error condition and assigning result; IsNumeric (Basic) vs IsNumber (worksheet). So much for consistency!

acceptable way to terminate a function early

for special cases

Variant is the generic type (can be number or string or… )

Code in UNSWGrade

Page 35: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Quiz: Can you improve this program?

•  Suppose someone wants to apply the Z-formula (a made-up formula):

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 35

•  to three different pairs of (H,T) –  H = 10000; T = 249 –  H = 12000; T = 271 –  H = 14000; T = 295

•  The person wrote the program on the next slide. What can be done better?

Z = H(1

2732� 1

T 2)

Page 36: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 36

Quiz (continued) Option Explicit Const T0 = 273 Sub Modular() Dim H1 As Double, H2 As Double, H3 As Double Dim T1 As Double, T2 As Double, T3 As Double Dim Z1 As Double, Z2 As Double, Z3 As Double H1 = 1e4: H2 = 12e3: H3 = 14e3: T1 = 249: T2 = 271: T3 = 295: Z1 = H1*(1/T0^2 - 1/T1^2) Z2 = H2*(1/T0^2 - 1/T2^2) Z3 = H3*(1/T0^2 - 1/T3^2)

MsgBox "Z1 = " & Format(Z1,"0.000") & "; " & _ "Z2 = " & Format(Z2,"0.000") & "; " & _ "Z3 = " & Format(Z3,"0.000") & "."

End Sub

Page 37: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Modular structure

•  Identical work should be performed by a function rather than repeating the code

•  Makes code easier to maintain and understand –  Hide the details of the calculation

•  Let us use a function to calculate the Z-formula this time

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 37

Code in Modular

Page 38: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Quiz: Do these two functions do the same thing?

Answer: It depends. •  If you use the functions from a worksheet, they are the same. •  If you call these functions from a sub or a function, then they

behave differently.

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 38

Function Func1(x As Double) As Double Func1 = 3 * x + 1

End Function

Function Func2(x As Double) As Double x = 3 * x Func2 = x + 1

End Function

Page 39: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Let us see what the differences are

Sub RunFunc1()

Dim x As Double Dim y As Double x = 2 y = Func1(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function Func1(x As Double) As Double

Func1 = 3 * x + 1 End Function

Sub RunFunc2()

Dim x As Double Dim y As Double x = 2 y = Func2(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function Func2(x As Double) As Double

x = 3*x Func2 = x + 1

End Function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 39

y = 7 y = 7

x = 2 x = 6

Page 40: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

What if I change the identifier from x to something else in the function?

Sub RunFunc2()

Dim x As Double Dim y As Double x = 2 y = Func2(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function Func2(x As Double) As Double

x = 3*x Func2 = x + 1

End Function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 40

y = 7

x = 6

Sub RunFunc3()

Dim x As Double Dim y As Double x = 2 y = Func3(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function Func3(notX As Double) as Double

notX = 3*notX Func3 = notX + 1

End Function

y = 7

x = 6

Page 41: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ByVal and ByRef

Sub RunFuncByVal()

Dim x As Double Dim y As Double x = 2 y = FuncByVal(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function FuncByVal(ByVal x As Double) as double

x = 3*x FuncByVal = x + 1

End Function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 41

y = 7

x = 2

Sub RunFuncByRef()

Dim x As Double Dim y As Double x = 2 y = FuncByRef(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function FuncByRef(ByRef x As Double) As Double

x = 3*x FuncByRef = x + 1

End Function

y = 7

x = 6

Page 42: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ByVal

Sub RunFuncByVal()

Dim x As Double Dim y As Double x = 2 y = FuncByVal(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function FuncByVal(ByVal x as double) as double

x = 3*x FuncByVal = x + 1

End Function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 42

y = 7

x = 2

To understand ByVal, we need to see what happens inside computer memory

Memory space for RunFuncByVal

y

x

7

2

Memory space for FuncByVal

x 6

If ByVal is used, the function allocates a separate memory space for the variable. The “x” in the sub is different from the “x” in the function and is not affected by the “x” in function.

Page 43: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ByRef

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 43

y = 7

x = 6

Memory space for RunFuncByRef

y

x

7

2

Memory space for FuncByRef

No memory is allocated for x and the function is allowed to

manipulate x in the sub

If ByRef is used, the function is given permission to manipulate the variable specified

Sub RunFuncByRef()

Dim x As Double Dim y As Double x = 2 y = FuncByRef(x) MsgBox "y = " & y MsgBox "x = " & x

End Sub Function FuncByRef(ByRef x As Double) as double

x = 3*x FuncByRef = x + 1

End Function

Page 44: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Quiz: What are the values of x and y at the end of the sub?

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 44

Sub RunFuncByRefByVal() Dim x As Double: Dim y As Double: Dim z As Double x = 2: y = 10 z = FuncByRefByVal(x,y) MsgBox "z = " & z MsgBox "x = " & x MsgBox "y = " & y

End Sub Function FuncByRefByVal(ByRef x As Double, ByVal y As

Double) As Double x = 3*x y = 5*y FuncByRefbyVal = x + y

End Function

z = 56

y = 10

x = 6

Page 45: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 45

Parameters revisited •  Values passed to procedures are called arguments •  Variables defined to hold these values are called

parameters •  Parameters are local variables, like ones declared

using Dim  •  Data can be passed in two different ways:

–  by value (argument is expression, only value transferred)

–  by reference (argument is variable, parameter acts as a temporary alias)

–  keywords ByVal and ByRef specify which •  If a function is called from a worksheet, ByVal is always use. •  If a function/sub is called from another function/sub, ByRef is

assumed if omitted

Page 46: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 46

Example: Swapping values Sub  Swap(ByRef  v1  As  Variant,  ByRef  v2  As  Variant)  

 Dim  tmpVal  As  Variant    

 tmpVal  =  v1    v1  =  v2    v2  =  tmpVal    

End  Sub    y  =  -­‐23.5:  z  =  6  Call  Swap(y,  z)              '  what  are  the  values  of  y  and  z?  

We used the Variant type so the procedure can be used to exchange the contents of variables any fundamental type, except objects. This is the only recommended use for Variants.

Motivation: imagine exchanging the positions of an apple and an orange on the table in front of you.

Now do it again using just one hand!

Code in swap

Page 47: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 47

Example: Parachutist Velocity Profile

Velocity of an object of mass m falling under the influence of gravity and subject to drag is

Where v0 is the initial velocity, g is acceleration due

to gravity (m s−2) and cd is the drag coefficient (in kg s−1)

The exponential factor decays in magnitude, so the velocity asymptotically approaches g m/ cd

For a free-falling 70kg parachutist with cd = 12.5, this terminal velocity is ~55 m s−2 (200km/hr)

)1()( )/()/(0

tmc

d

tmc dd ecmgevtv −− −+=

Page 48: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 48

Parachutist Velocity Profile, continued

When the parachutist pulls the rip-cord (t = tc), the same equation applies subsequently except that...

•  v0 is the velocity at the instant the parachute opens

•  there is a new, larger, drag coefficient cdp

•  the time parameter is t − tc

instead of t

tc = 6s

Page 49: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 49

Parachutist Simulation

•  We can write a function that, given all parameters, calculates the velocity at any time t  

•  The function can be filled down a worksheet •  The algorithm, expressed in pseudocode, is

If  t  <  tc  Then    '  still  in  free-­‐fall    Calculate  free-­‐fall  velocity  

Else    Calculate  velocity  at  time  tc    Store  in  velocityChute    Calculate  velocity  using  cdp  and  velocityChute  

End  If  

Page 50: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Someone’s implementation

Function VelX(t, g, m, cd, v0, tc, cdp) If t <= tc Then 'Compute velocity of freefall VelX = v0 * Exp(-cd / m * t) _ + g * m / cd * (1 - Exp(-cd / m * t)) Else ' compute velocity when parachute is first deployed v0p = v0 * Exp(-cd / m * tc) _ + g * m / cd * (1 - Exp(-cd / m * tc)) ' compute velocity after parachute is deployed VelX = v0p * Exp(-cdp / m * (t - tc)) _ + g * m / cdp * (1 - Exp(-cdp / m * (t - tc))) End If End Function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 50

How can you improve this implementation?

Code in ParaBad

Page 51: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

1.  The decay expression has its own function: Function  Decay(drag  As  Double,  mass  As  Double,  _            time  As  Double)  As  Double  

       Decay  =  Exp(-­‐drag  *  time  /  mass)  

End  Function  

2.  The terminal velocity has a named variable (to make the expression more meaningful). We’ve called it velocityLimit  

3.  The structure of the algorithm (before/after chute, common components) makes the solution easy to follow, especially compared to the massive IF formula that would be required without the coded function

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 51

Implementation notes

tmcde )/(−

Page 52: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 52

Another Worked Example

•  Fluid flow: calculating the Moody friction factor in a pipe with a circular cross-section and certain properties, carrying fluids of various kinds

•  Solution space has three distinct regions, requiring a classification of the flow type

•  We use the model described at

http://www.lmnoeng.com/moody.php

•  Other references on sheet

Page 53: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

Advanced language features that are not essential

knowledge (but useful to know) are marked

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 53

Topic format

Page 54: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 54

Select Case

Multiway selection with a common expression: VBA has a simpler way than many If statements

Select  Case  expression  

 Case  value      statements    Case  value1,  value2      statements    Case  value1  To  value2      statements    Case  Is  >  value      statements    Case  Like  pattern        statements    Case  Else      statements  

End  Select  

multiple values grouped

inclusive range of values

open range of values

values matching pattern

single value

evaluated first, then matched against each label

all unmatched values

any

num

ber

of e

ach

of t

hese

ca

n oc

cur

Page 55: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 55

Select Case example

•  Classify a single-character string c   Select  Case  UCase(c)      Case  "A","E","I","O","U"        sym  =  "vowel"      Case  "0"  To  "9"        sym  =  "digit"      Case  "A"  To  "Z"            '  or  Case  Like  "[A-­‐Z]"        sym  =  "consonant"      Case  ""        sym  =  "empty"      Case  Like  "??*"        sym  =  "more  than  one  char"      Case  Else        sym  =  "punctuation"    End  Select  

use of UCase saves repeating upper and

lower case letter rules

Page 56: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 56

Strings

•  A string is a sequence of characters •  Strings in OO Basic can be of virtually any length

(including zero, of course) •  Components are characters

–  represented internally as codes with numeric value from 0 to 255*

–  each code is interpreted by an output device as a graphic character or special action

–  functions Chr and Asc convert between character and numeric code

* For conventional ASCII characters, OO Basic also supports Unicode characters.

Page 57: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 57

Literal Strings

•  String constants are enclosed in double-quote characters "…" (not single quotes)

•  How to include a double-quote as a member of the string (the delimiter-as-data problem)? Write it twice, as in

"Reference: ""OpenOffice for Experts""" •  Empty string is denoted by ""

•  & concatenates (joins) two strings –  "c" & "at" (= "cat") "cat" & "ch" & "-22"

Page 58: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 58

String Comparison

•  relational (comparison) operators –  compare individual characters, so

"cat" < "dog" (because "c" < "d") "cat" < "cave" (because "t" < "v") "cat" < "catastrophe" (prefix) "Cat" < "cat" (case sensitive)

–  can change to case-insensitive comparison (to make "Cat" = "cat") by placing

Option  Compare  Text  

at the top of the module

Page 59: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 59

String Matching

•  The Like operator allows a string expression to be tested against a pattern that includes wildcards

strData Like "pattern"

•  The pattern consists of ? any single character # any digit character * zero or more characters

[list] any character in list [!list] any character not in list

Page 60: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W6 slide 60

String Matching Examples

Assume the following values str1  =  "cat":  str2  =  "Route66":  str3  =  "2*3"  

Expression Value Reason str1  Like  "cat"   True   ordinary chars OK

str1  Like  "c?t"   True   ? matches the character a  str1  Like  "c"   False   must match whole of string str2  Like  "*##"   True   ends in two digits str2  Like  "[A-­‐Z]*"   True   [A-­‐Z]  matches any capital str2  Like  "*[!6]"   False   can't match non-6 at end str2  Like  "*[!6]*"   True   (you work it out!) str3  Like  "*3"   True   * matches 2*  str3  Like  "#[*]?"   True   to match special chars *  [  ?  

literally, enclose in [  ]  

Page 61: Week 5 Control Structures for Programming: Selection ... · PDF fileControl Structures for Programming: Selection, Functions ... • Subprogram structure SubFoo() ... – iteration

ENGG1811 © UNSW, CRICOS Provider No: 00098G W5 slide 61

Summary

•  Boolean expressions represent the result of decisions

•  If-Then used for selection (three forms) •  Functions return a single value, can accept any

number of parameters •  Parameters are local variables that are given

initial values when the function is called •  OO Basic functions can be used in worksheet

formulas •  Interpreter can be used to trace a program to

assist in debugging