Module 4: Processes Recipes from Scratch - UBC …cs101/2012W1/slides/Programming... · Module 4:...
Transcript of Module 4: Processes Recipes from Scratch - UBC …cs101/2012W1/slides/Programming... · Module 4:...
CPSC 101 – 2012W T1 2
Here is a recipe for Jello Instant Pudding
1. put 3 cups of milk in a bowl
2. add entire contents of package
3. whisk for 2 minutes
4. transfer to serving bowls
5. let stand for 3-5 minutes
6. serve!
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 3
Learning Goals: at the end of this module, you will be able to:
recognize and explain the five essential properties of an algorithm:
input specified
output specified
definiteness
effectiveness
finiteness
Module 4: Processes
CPSC 101 – 2012W T1 4
Learning Goals (continued)
recognize and explain the concepts of
sequences of instructions,
variables,
loops,
functions,
conditional statements,
and arrays
in short programs specified in a programming language such as JavaScript, or in other clearly expressed processes (which may or may not be computer related)
Module 4: Processes
CPSC 101 – 2012W T1 5
Learning goals (continued):
determine, simulate and explain how short programs or program fragments work
make small modifications to short program fragments to achieve clearly specified tasks
explain and simulate simple algorithms for fundamental problems such as searching and sorting
Module 4: Processes
CPSC 101 – 2012W T1 6
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 7
Module 4.1: Programs and algorithms
Exercise: write an algorithm for making a peanut butter and jam sandwich. Your algorithm can use:
peanut butter
sliced bread
jam
knife
spoon
plate
CPSC 101 – 2012W T1 8
Did your group succeed in getting a proper sandwich made?
a) Yes, right away.
b) Yes, after 1-2 revisions to the instructions
c) Almost.
d) No.
Module 4.1: Programs and algorithms
?
CPSC 101 – 2012W T1 9
What was the main point you took away from the exercise?
a) Making sandwiches is hard.
b) Humans are smart.
c) Specifying a process precisely is hard.
d) Carrying out precise instructions is hard.
Module 4.1: Programs and algorithms
?
CPSC 101 – 2012W T1 10
Processes (programs, algorithms)
are everywhere
allow us to make computers and people do things they otherwise couldn’t.
Can you come up with 3 examples of “programs” not primarily meant to be executed by computers??
Module 4.1: Programs and algorithms
CPSC 101 – 2012W T1 11
Jumping in at the deep end:Processing: Depth [processing.org]
Scratch: Dancing triangles [scratch.mit.edu]
Don’t Panic!It’s OK to not understand parts of a program
Web search can help
Experimentation aids understanding
Module 4.1: Programs and algorithms
CPSC 101 – 2012W T1 12
Fundamental concepts:
Instructions (input, output, drawing, math, …)
Sequences of instructions
Variables
Loops / repetition (repeat, until, while, for)
Procedures / functions
Conditional statements (if, else)
Arrays
Module 4.1: Programs and algorithms
CPSC 101 – 2012W T1 13
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 14
Here is a more interesting recipe for Duck breast with Seville orange & savoy cabbagehttp://www.bbcgoodfood.com
Ingredients (for 4):
4 duck breasts
1 large Seville orange, zested and juiced
2 tbsp honey
2 cloves
1 cinnamon stick
chicken stock fresh, cube or concentrate, made up to 300ml
1 savoy cabbage, quartered, heart removed and shredded
butter
mashed potato, to serve
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 15
Duck breast recipe (continued)
Preparation:
1. Heat a non-sticking frying pan.
2. Put in the duck breasts, skin side down, then turn down the heat and leave for 10 minutes until the fat on the duck is golden brown and crisp.
3. Pour off the fat, turn the duck over.
4. Then stir together the orange juice, zest and honey and add to the pan with the cloves, cinnamon and stock.
5. Simmer for 10-12 minutes.
6. Remove the duck and rest in a warm place for 5 minutes. Reduce the sauce a little and season.
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 16
Duck breast recipe
Preparation (continued)
7. Cook the cabbage in a little butter until wilted but still bright green.
8. Slice the duck.
9. Serve with the cabbage, sauce and some creamy mash.
Bon appétit!
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 17
Which fundamental concepts are used by this recipe?
Instructions?
Sequences of instructions?
Variables?
Loops / repetition?
Procedures / functions?
Conditional statements?
Arrays?
Module 4.2: Recipes and variables
?
CPSC 101 – 2012W T1 18
Challenges:
Explain how the recipe does / does not satisfy each of the defining properties of an algorithm.
Modify the recipe so it better satisfies the defining properties of an algorithm.
Prepare the dish for someone close to you
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 19
Duck breast recipe (continued)
Preparation:
1. Heat a non-sticking frying pan.
2. Put in the duck breasts, skin side down, then turn down the heat and leave for 10 minutes until the fat on the duck is golden brown and crisp.
3. Pour off the fat, turn the duck over.
4. Then stir together the orange juice, zest and honey and add to the pan with the cloves, cinnamon and stock.
5. Simmer for 10-12 minutes.
6. Remove the duck and rest in a warm place for 5 minutes. Reduce the sauce a little and season.
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 20
Duck breast recipe
Preparation (continued)
7. Cook the cabbage in a little butter until wilted but still bright green.
8. Slice the duck.
9. Serve with the cabbage, sauce and some creamy mash.
Bon appétit!
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 21
Recall:
Ingredients (for 4):
4 duck breasts
1 large Seville orange, zested and juiced
2 tbsp honey
2 cloves
1 cinnamon stick
chicken stock fresh, cube or concentrate, made up to 300ml
1 savoy cabbage, quartered, heart removed and shredded
1 tbsp butter
What do we do if we have k people instead of 4?
Module 4.2: Recipes and variables
?
CPSC 101 – 2012W T1 22
Duck breast with Seville orange & savoy cabbagehttp://www.bbcgoodfood.com
Ingredients (for k people):
k duck breasts
k/4 large Seville orange, zested and juiced
k/2 tbsp honey
k/2 cloves
k/4 cinnamon stick
chicken stock fresh, cube or concentrate, made up to 75k ml
k/4 savoy cabbages quartered, heart removed and shredded
k/4 tbsp butter
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 23
Duck breast with Seville orange & savoy cabbagehttp://www.bbcgoodfood.com
Ingredients (for numPeople people):
numPeople duck breasts
numPeople/4 large Seville orange, zested and juiced
numPeople/2 tbsp honey
numPeople/2 cloves
numPeople/4 cinnamon stick
chicken stock fresh, cube or concentrate, made up to 75 * numPeople ml
numPeople/4 savoy cabbages quartered, heart removed and shredded
numPeople/4 tbsp butter
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 24
Using variables makes programs
more versatile
We can make duck breasts for any number of people.
easier to understand (use meaningful variable names!!)
Consider these two examples:s = s * 1.015 + 1250;
andsalary = salary * (1 + percentIncrease) + bonus;
easier to modify, extend and adapt
Module 4.2: Recipes and variables
CPSC 101 – 2012W T1 25
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 26
Common types of instructions:
input/output
graphics (display object, move object, set visual properties ...)
audio (play sound, ...)
timing (wait, ...)
variable assignments
Module 4.3: Loops
CPSC 101 – 2012W T1 27
Loops are used for repeating parts of a process
Types of loops:
Repeat ... k times
Repeat ... until condition
While condition do ...
Module 4.3: Loops
CPSC 101 – 2012W T1 28
Example: loops in Scratchto make the triangle turn faster while still ending at "home base”, I should
a) Increase 36
b) Increase 10
c) Increase 0.01
d) None of the above
Module 4.3: Loops
?
CPSC 101 – 2012W T1 29
Assume that
max and i are variables.
do something is an unspecified action.
What do you think each piece of code does?
a) for (i=1; i <= max; i = i + 1) { do something }
b) for (i=0; i < max; i = i + 1) { do something }
c) for (i=1; i <= max; i = i + 2) { do something }
d) for (i=max; i >= 1; i = i - 1) { do something }
Which one differs from the rest?
Module 4.3: Loops
?
?
CPSC 101 – 2012W T1 30
Note thatfor (i=1; i <= max; i++){ so something}
is the same asi=1;while (i <= max) { so something i++;}
Module 4.3: Loops
loop body
CPSC 101 – 2012W T1 31
How often is the body of the following for loop executed?
for (n=1; n <= max; n = n + 1) { do something }
a) once
b) max times
c) max-1 times
d) max+1 times
e) none of the above
Module 4.3: Loops
?
CPSC 101 – 2012W T1 32
How often is the body of the following for loop executed?
for (n=0; n <= max; n = n + 1) { do something }
a) once
b) max times
c) max-1 times
d) max+1 times
e) none of the above
Module 4.3: Loops
?
CPSC 101 – 2012W T1 33
How often is the body of the following for loop executed?
for (n=0; n < max; n = n + 1) { do something }
a) once
b) max times
c) max-1 times
d) max+1 times
e) none of the above
Module 4.3: Loops
?
CPSC 101 – 2012W T1 34
What is the value of variable n after the loop has finished executing?
n=0;while (n < max) { do something; n++;}
a) 1b) maxc) max – 1d) max + 1e) Not enough information to tell
Module 4.3: Loops
?
CPSC 101 – 2012W T1 35
What is the value of variable n after the loop has finished executing?
For (n = 0; n <= max; n = n + 1){ do something that does not modify n; n++;}
a) 1
b) max
c) max – 1
d) max + 1
e) Not enough information to tell
Module 4.3: Loops
?
CPSC 101 – 2012W T1 36
To figure out what a piece of code does:
1. Model – form a hypothesis of what a piece of code does
often done through running / simulating it for simple / small inputs.
2. Predict – predict what it will do for inputs not yet tried / simulated
3. Experiment – run / simulate to check your prediction
4. Refine – modify your hypothesis based on the result from the experiment; continue from Step 2.
Note: This is also known as the scientific method.
Module 4.3: Loops
CPSC 101 – 2012W T1 37
Tricks to figure out why a piece of code doesn't do what you think it does:
Simulating the piece of code:
Use pencil and paper to trace the values of all important variables through the statements.
Experimenting with the piece of code:
Instrument the code with additional output statements, so you can see the values of variables at various points of execution.
Module 4.3: Loops
CPSC 101 – 2012W T1 38
Tricks to figure out why a piece of code doesn't do what you think it does (continued)
Automatic checks
Use if statements (covered later) that ascertain whether or not the conditions you expect to hold actually hold.
Use statements that catch incorrect behaviour (deviations from your expectations).
Use a debugger
A (more advanced) tool that helps you do this types of checking.
Module 4.3: Loops
CPSC 101 – 2012W T1 39
Rewrite the following loop as a for loop:
sum = 0;i = 1;while( i <= 5) { sum = sum + i; i++;}
Hint: To check your solution, trace the values of sum and i through all iterations of the loop (both versions) and make sure that they match.
Module 4.3: Loops
?
CPSC 101 – 2012W T1 40
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 41
Which of these are advantages of using functions:
a) They break up a big process into smaller parts
b) They give a name to part of a process
c) They allow you to re-use components (share) parts between processes, and between people
d) All of the above.
e) None of the above.
Module 4.4: Functions
?
CPSC 101 – 2012W T1 42
Breaking up a big process into smaller partsHelps simplify the big process
We can concentrate on a smaller part, which is easier
Smaller parts have fewer details and can be broken down further if necessary.
Giving a name to part of a processImproves the readability of your processes
So you will see “hang the LCD TV on the front wall”
Instead of 50 instructions explaining how to do this.
Module 4.4: Functions
CPSC 101 – 2012W T1 43
Re-using component parts between processes, and between people
More reliable: you only need to get it right once.
Easier to update: you only need to make a change once.
Teamwork: each team member writes some of the functions.
Abstraction: except for the person writing the function, you only need to know what it does, not how it works.
Module 4.4: Functions
CPSC 101 – 2012W T1 44
Example: building a housebuild the foundation
build the frame
build the floors
do the electrical work
add the plumbing
build drywalls
...
Module 4.4: Functions
CPSC 101 – 2012W T1 45
Build a housefoundation
build frame...
...hammer a nail
build floors...
...hammer a nail
Module 4.4: Functions
Re-Use
CPSC 101 – 2012W T1 46
Build a house
build frame
......
hammer a nail
Build a dog house
...
...hammer a nail
Module 4.4: Functions
CPSC 101 – 2012W T1 47
Modify the following function:
function showTip(amount) { var tip; tip = amount * 0.12; document.write("the tip is: $" + tip);}
to make the tip rate (set to 12% above) a parameter.
Module 4.4: Functions
?
CPSC 101 – 2012W T1 48
Answer:
function showTip(amount, tipRate) { var tip; tip = amount * tipRate; document.write("the tip is: $" + tip);}
Now modify the function to return the tip instead of displaying it into an HTML document.
Module 4.4: Functions
?
CPSC 101 – 2012W T1 49
body includes variable declarations,
instructions (such as assignment stmts)
return statement(s)
function calculateTip(amount)
{var tip;tip = amount * 0.12;return(tip)}
function declaration includes name and (parameters)
Module 4.4: Functions
Anatomy of a Javascript function:
CPSC 101 – 2012W T1 50
function calculateTip(amount)
{var tip;tip = amount * 0.12;return(tip)}
Anatomy of a Javascript function: watch for syntax
the parentheses in the declaration (must be present even if the function has no parameters!)
the { and } around the body
the semicolons (at the end of each statement, optional after the return statement)
Module 4.4: Functions
CPSC 101 – 2012W T1 51
Things to remember about functions:Using a function requires two parts:
declaration (where we define the function).
call (where we execute it).
Module 4.4: Functions
<html><head> <script type="text/javascript"> function showTip(amount) { var tip = amount * 0.12; document.write("<p>Tip = " + tip + "</p>"); } </script></head><body> <script type="text/javascript"> showTip(150); </script></body></html>
CPSC 101 – 2012W T1 52
Things to remember about functions:Parameters
can be seen as special variables that are set to certain values when the function is called and before the body is executed.
are used to pass data into a function.
Variables declared inside a function are private to that function and cannot be accessed outside of it.
Module 4.4: Functions
CPSC 101 – 2012W T1 53
Things to remember about functions (continued):
Return statements
are used to pass data (a result) back from the function to the place from where it was called.
After a return statement is executed, execution of the function stops immediately (even if further statements follow in the function declaration)!
Functions can call other functions (or even themselves – but be very careful with this, since it's possible for this to go on forever).
Module 4.4: Functions
CPSC 101 – 2012W T1 54
Things to remember about functions (continued):
Functions may have zero parameters (if they do not require input data).
Functions may declare zero variables.
Functions do not need to use a return statement if they have no data to return to the calling function.
Functions may have more than one return statement, but only one of them ever gets executed in any given call.
Module 4.4: Functions
CPSC 101 – 2012W T1 55
What is the value of y at the end of confuse(10)?a) 10
b) 20
c) 30
d) 40
e) Some other value
function confuse(y){ var x;
x = 2 * y; y = y + x;
return (x);}
Module 4.4: Functions
?
CPSC 101 – 2012W T1 56
What value is returned by doubleConfuse(3,10)?a) 3
b) 13
c) 23
d) 33
e) Another value
function confuse(y){ var x = 2 * y; y = y + x; return x;}
function doubleConfuse(a,b){ var x = a + confuse(b); return x;}
Module 4.4: Functions
?
CPSC 101 – 2012W T1 57
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 58
What will the value of x be after executing the following?
x = -10;if (x < 0) { x = x * 1.195;} else { x = x * 1.015;}
a) -11.95
b) -10.15
c) -10
d) 0
Module 4.5: Conditional statements
?
CPSC 101 – 2012W T1 59
Let's revisit our calculateTip function:
function CalculateTip(amount, tipRate){ tip = amount * tipRate; return (tip);}
What if we want to determine the tip amount based on service?
If service is "good" (7 or more on a scale from 1 to 10) then give a good tip (add an extra 3%).
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 60
Assume we have a parameter serviceLevel.
To determine the tip amount:
if (serviceLevel >= 7) {
adjustedRate = tipRate + 0.03; // +3%
} else {
adjustedRate = tipRate; // no extra tip
}
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 61
Exercise: what if we want to have 3 different levels of tip?
Good / Normal / Terrible
Write out the new function in full, including theparameters, return value, etc.
First write your solution individually
Then compare it to your neighbour's.
If you have a laptop, try it out!
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 63
if (serviceLevel == 10) { adjustedRate = baseRate * 2;
} else if (serviceLevel < 3) { ... } else { ...}
Logical condition (= something that must be true or false)
else if & else are optional: you can have just an "if"
you are used to {brackets} now
Module 4.5: Conditional statements
Anatomy of a conditional statement:
CPSC 101 – 2012W T1 64
What will the value of x be after executing the following?
x = -10;if (x = 0) { x = x * 1.195;} else { x = x * 1.015;}
a) -11.95
b) -10.15
c) -10
d) 0
Module 4.5: Conditional statements
?
CPSC 101 – 2012W T1 65
Caution: two common mistakes:
1. if (serviceLevel = 10) {..}
2. if (serviceLevel == 10); {..}
always use “== “ to test equality
No semicolon here!
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 66
Useful operators:
== (equal)
if (serviceLevel == 10) {…}
!= (unequal)
if (serviceLevel != 10) {…}
&& (and)
if ((food > 7) && (service > 7)) {…}
|| (or)
if ((food < 3) || (service < 3)) {…}
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 67
In summary: conditional statements
can be used to alter the flow of your program depending on user input or intermediate results
can help you make your program more flexible
Module 4.5: Conditional statements
CPSC 101 – 2012W T1 68
??
Loops Functions Conditionals
functionbody
loop body
ifbranch
elsebranch
Module 4.5: Conditional statements
Flow of control:
CPSC 101 – 2012W T1 69
Module 4: Processes
Module Outline
Programs and algorithms.
Recipes and variables.
Loops.
Functions.
Conditional statements.
Arrays.
CPSC 101 – 2012W T1 70
Consider a student's grade, computed based on marks for four assignments:
var mark1 = 83;var mark2 = 79;var mark3 = 58;var mark4 = 97;var grade = (mark1+mark2+mark3+mark4)/4;
How should we write the code if there were twelve assignments instead? If there were one thousand?
Module 4.6: Arrays
CPSC 101 – 2012W T1 71
Arrays are a means to store tabular data:
var colors = new Array("red","brown”,"blue");
This is equivalent to:
var colors = new Array();colors[0] = "red";colors[1] = "brown";colors[2] = "blue";
Module 4.6: Arrays
“red” “brown” “blue”0 1 2
CPSC 101 – 2012W T1 72
What is the value of colors[1] invar colors = new Array("red","brown","blue");
a) “red”
b) “brown”
c) “blue”
d) none of the above
Module 4.6: Arrays
?
CPSC 101 – 2012W T1 73
A common mistake: the first element of an array has index 0, not 1!!
Hence, invar colors = new Array("red","green”,"blue");
the index (position) of “red” is 0, etc.
Note:
Normal folks count 1, 2, 3,…
Computer Scientists count 0, 1, 2,…
That's why the introduction was module 0, not module 1!
Module 4.6: Arrays
CPSC 101 – 2012W T1 74
What is the value of n invar colors = new Array("red","green","blue");var n = colors.length;
a) 0b) 1c) 3d) 4
Module 4.6: Arrays
?
CPSC 101 – 2012W T1 75
We use indices to access array valuescolors[2] = "magenta";
After this assignment statement the value stored in slot 2 of the array changes to “magenta”:
Module 4.6: Arrays
“red” “brown” “blue”0 1 2
“red” “brown” “magenta”0 1 2
CPSC 101 – 2012W T1 76
Example: calculating a grade by averaging over marks, stored in an array:
var marks = new Array(83, 79, 58, 97);var total = 0;for (var i = 0; i < marks.length; i++) { total = total + marks[i];}var grade = total / marks.length;
This loop will compute the correct answer no matter how many marks are involved (except 0).
Module 4.6: Arrays
CPSC 101 – 2012W T1 77
Arrays can be nested (that is, the elements of an array can themselves be arrays):var phoneBook = new Array();phoneBook[0]= new Array("Ada", "604-123-4567");phoneBook[1]= new Array("Anne", "604-234-4567");phoneBook[2]= new Array("Bruno", "604-345-4567");phoneBook[3]= new Array("Gillian","604-456-4567");phoneBook[4]= new Array("Maria", "604-567-4567");phoneBook[5]= new Array("Yong", "604-678-9876”);
Module 4.6: Arrays