CS105 Introduction to Social Network Lecture: Yang Mu UMass Boston.
Loops - David R. Cheriton School of Computer Sciencedvogel/cs105f16/materials/lectures/05...
Transcript of Loops - David R. Cheriton School of Computer Sciencedvogel/cs105f16/materials/lectures/05...
LoopsVariable ScopeRemappingNested Loops
CS105 | 05 Loops 1
Donald Judd
CS105 | 05 Loops 2
judd
CS105 | 05 Loops 3
while (expression) {
statements
}
Four Loop Questions
1. What do I want to repeat? - a rect
2. What do I want to change each time? - the y position of the rect
3. Where does it start, how does it change?- start at y = 10, draw a rect every 20 pixels
4. How long should it repeat?- until it reaches the bottom of the canvas
CS105 | 05 Loops 4
code block
update
testexpression
initialisationAnatomy of a While Loop
CS105 | 05 Loops 5
See “05 Loops (trace)”
CS105 | 05 Loops 6
Debugging Tracethrough
CS105 | 05 Loops 7
draw() frames vs. while loop iterations
§ the code block in draw is repeated every frame
§ the code block in while is repeated every loop iteration
CS105 | 05 Loops 8
void draw() {
while (x < width) {
}
}
loop
iter
atio
ns
fram
es
What do you see after 5 frames?
CS105 | 05 Loops 9
int a;
void draw() {
background(200);
a = 20;
while (a < width) {
ellipse(a, 50, 20, 20);
a = a + 20;
}
}
lines_rs
CS105 | 05 Loops 10
draws lines randomly spaced across
canvas width
lines_es
CS105 | 05 Loops 11
draws an exact number of lines
spaced equally across canvas width
notes:
• using width/height
in variable assignment
• float vs. int
• margins
lines_fs
CS105 | 05 Loops 12
draws an exact number of lines with
fixed spacing
variations and notes:
• counter variable
• position variable
• (line location a function of
counter)
• right to left variation
Common Logic Errors Leading to Infinite Loops
CS105 | 05 Loops 13
x = 0;
while (x < width); {
line(x, 10, x, height - 10);
x = x + 10;
}
Adding a semicolon after the boolean expression means no code block. Without a code block, the loop variable won't update.
The while statement will never end, and the program will freeze (infinite loop).
Fix this by removing the semicolon after the boolean expression.
x = 0;
while (x < width) {
line(x, 10, x, height - 10);
x = x - 10;
}
The loop variable is updated such that the loop condition will always be true.
The while statement will never end, and the program will freeze (infinite loop).
Fix this by ensuring that your code eventually makes the loop repetition expression false.
Debugging Loops
§ Test a single loop operation first (without a loop)
§ Simplify the loop operation
§ Slow down draw frames with frameRate(1)
§ Use println
CS105 | 05 Loops 14
x = 0;
println("start loop"); // debug
while (x < width) {
println("loop", x); // debug
line(x, 10, x, height - 10);
x = x + 10;
}
println("done loop"); // debug
What do you see after 5 frames?
CS105 | 05 Loops 15
int i;
int x;
void draw() {
background(200);
i = 0;
x = 20;
while (i < 5) {
ellipse(x, 50, 20, 20);
}
i = i + 1;
x = x + 20;
}
gradient
CS105 | 05 Loops 16
creates a grayscale gradient
example of varying more than one variable
(demos)
CS105 | 05 Loops 17
convert while loop to for loop
Assignment Operator “Short Forms”
These all add 1 to x (they are all equivalent):x = x + 1;
x += 1;
x++;
These both add 5 to x (they are both equivalent):x = x + 5;
x += 5;
Other examples// same as x = x + 10 * y;
x += 10 * y;
// same as x = x + random(-2, 2);
x += random(-2, 2);
CS105 | 05 Loops 18
increment operator
More Assignment Operator “Short Forms”
x--;
x -= 10;
x *= 10;
x /= 10;
CS105 | 05 Loops 19
decrement operator
coding
Anatomy of a For Loop
CS105 | 05 Loops 20
updatetest
expression
code block
initialization
When to use for or while loop?
for is a short form for while, and they’re interchangeable.
(You can always use while if you want)
CS105 | 05 Loops
update
testexpression
initialisation
updateinitializationtest expression
21
When to use for or while loop?
But sometimes one is easier to use in certain cases:
§ Use for to loop an exact number of repetitions:- I want 10 pacmen- I want 3 lines- I want random(3,11) lines
§ Use for to update by same amount:- I want to count by 10 from 0 to 100- I want lines spaced 10 pixels apart the width of the canvas
§ Use while to update by different amounts when you don’t need to loop an exact number of repetitions:- I want lines spaced 2 - 10 pixels apart the width of the canvas
CS105 | 05 Loops 22
Four Loop Questions
1. What do I want to repeat? - a line
2. What do I want to change each time? - the x position
3. Where does it start, how does it change?- start at x = 10, draw a line every 20 pixels
4. How long should it repeat?- I want to draw 7 lines
CS105 | 05 Loops
Use for to loop an exact number of times
23
lines_fs_for
CS105 | 05 Loops
Use for to loop an exact number of times(a for loop version of lines_fs)
// start line with margin from left
x = spacing / 2;
for (int i = 0; i < num; i++) {
line(x, 10, x, height - 10);
x += spacing;
}
24
Four Loop Questions
1. What do I want to repeat? - a line
2. What do I want to change each time? - the x position
3. Where does it start, how does it change?- start at x = spacing/2, draw a line every spacing pixels
4. How long should it repeat?- I want to draw 11 lines (equally spaced)
CS105 | 05 Loops
Use for to update by same amount
25
lines_es_for
CS105 | 05 Loops
Use for to update by same amount
for (float x = spacing / 2; x < width; x += spacing) {
line(x, 10, x, height - 10);
}
26
Four Loop Questions
1. What do I want to repeat? - a line
2. What do I want to change each time? - the x position
3. Where does it start, how does it change?- start at x = 0, increment x randomly between 2 and 20 pixels
4. How long should it repeat?- I want to draw lines all the way across the canvas
CS105 | 05 Loops
Use while to update by different amounts when you don’t need to loop an exact number of repetitions
27
lines_rs_for
CS105 | 05 Loops
You can do this with for, but easier/clearer with while
for (float x = 0; x < width; x += random (2, 20)) {
line(x, 10, x, height - 10);
}
28
What do you see after 1 frame?
CS105 | 05 Loops 29
int i;
int a;
void draw() {
background(200);
i = 0;
while (i < 1000000) {
a = int(random(0, 100));
point(a, a);
i++;
}
}
Scope
§ What parts of your code have access to a variable- i.e. what variables can a code
statement "see"
CS105 | 05 Loops 30CREDIT: http://www.biggamehunters.co.uk/
Global Scope
§ We have been declaring variables “outside” of functions- These are called global variables
§ Global variables can be used anywhere in a program after they are declared- They have global scope- They "remember" their value between calls to setup(), draw(), etc.- Built-in Processing variables are global
e.g. width, height, frameCount, mouseX, key
CS105 | 05 Loops 31
(see GS 52)
Local Scope
§ You can declare variables “inside” any code block- These are called local variables
§ Local Variables can be used anywhere in that code block after they're declared
§ recall, a code block is anything in between { and }- functions have code blocks- loops have code blocks- (conditionals have code blocks)
§ local variables cease to exist after the code block is exited- they have local scope
CS105 | 05 Loops 32
lines_es_local
CS105 | 05 Loops 33
void draw() {
background(200);
// x is a local variable only visible to draw()!
float x = spacing / 2;
while (x < width) {
line(x, 10, x, height - 10);
x += spacing;
}
}
Variable Scope Analogy
CS105 | 05 Loops 34
local(use it then throw it out)
global(remember it)
global(remember it and update it)
CS105 | 05 Loops 35
int w = 100;
int y = w;
void setup() {
int h = w * 3;
size(w, h);
}
void draw() {
background(240);
line(0, y, w, y);
int n = int(random(0, 500));
for(int i = 0; i < n; i++) {
float px = random(0, w);
float py = random(0, y);
point(px, py);
}
y--;
}
scope of w
scope of h
scope of n
scope of px
scope of y
scope of py
Computer Memory and Variables
CS105 | 05 Loops 36
y
100
w
100
mouseX
67
TWO_PI
6.2831
int w = 100;
int y = w;
void setup() {
int h = w * 3;
size(w, h);
}
void draw() {
background(240);
line(0, y, w, y);
int n = int(random(0, 5
for(int i = 0; i < n; i
float px = random(0,
float py = random(0,
point(px, py);
}
Computer Memory and Variables
CS105 | 05 Loops 37
y
100
w
100
mouseX
67
TWO_PI
6.2831
setup() variables
h
300
int w = 100;
int y = w;
void setup() {
int h = w * 3;
size(w, h);
}
void draw() {
background(240);
line(0, y, w, y);
int n = int(random(0, 5
for(int i = 0; i < n; i
float px = random(0,
float py = random(0,
point(px, py);
}
Computer Memory and Variables
CS105 | 05 Loops 38
y
100
w
100
mouseX
67
TWO_PI
6.2831
setup() variables
h
300
int w = 100;
int y = w;
void setup() {
int h = w * 3;
size(w, h);
}
void draw() {
background(240);
line(0, y, w, y);
int n = int(random(0, 5
for(int i = 0; i < n; i
float px = random(0,
float py = random(0,
point(px, py);
}
When to use local variables
§ When you don't need to "remember" the value after the code block completes- a loop variable- an intermediate calculation- to re-use a common value in a function call
CS105 | 05 Loops 39
(local variable for intermediate calculation)
CS105 | 05 Loops 40
void draw() {
…
// calculate start and end angles
float start = radians(dir – mouthOpening/2);
float end = radians(dir + mouthOpening/2));
// use those angles to draw the arc
arc(width/2, height/2, mouseX, mouseX, start, end);
…
}
local variables
local variables
(local variable for re-use)
CS105 | 05 Loops 41
void draw() {
…
} else if (shape == 3) {
// half size
int hs = size / 2;
triangle(mouseX - hs, mouseY + hs,
mouseX, mouseY – hs,
mouseX + hs, mouseY + hs);
}
…
}
local variable
(out of scope errors with local variables)
CS105 | 05 Loops 42
void draw() {
…
} else if (shape == 3) {
triangle(mouseX - hs, mouseY + hs,
mouseX, mouseY – hs,
mouseX + hs, mouseY + hs);
// half size
int hs = size / 2;
}
…
}
cannot find variable named "hs"
hs is defined after it is used
(out of scope errors with local variables)
CS105 | 05 Loops 43
int x = 0;
void setup() {
// local variable
// only accessible to setup()
int speed = 2;
}
void draw() {
ellipse(x, 50, 20, 20);
// this will cause an error: there is no
// variable called 'speed' accessible to draw()
x += speed;
}
cannot find variable named "speed"
speed is defined as a local variable in setup()
(logic errors with local variables)
CS105 | 05 Loops 44
void draw() {
int x;
ellipse(x, 50, 20, 20);
x += 2;
}
x is declared as a local variable and it will be assigned a default
value of 0 each frame
the local variable x will be incremented, but then x will be thrown away as soon as draw
finishes
(logic errors with local variables)
CS105 | 05 Loops 45
int x = 0;
void draw() {
int x;
ellipse(x, 50, 20, 20);
x += 2;
} the local variable x will be incremented, but then x will be thrown away as soon as draw
finishes
x is declared as a local variable and it will "shadow" (hide) the
global variable x.
The local variable x will be assigned a default value of 0
each frame
What does this loop output?
CS105 | 05 Loops 46
int a = 2;
void setup() {
int a = 3;
for (int i = 0; i < a; i++) {
println("duck");
}
println("goose");
}
Changing Multiple “Things” in One Loop
1. What do I want to repeat? - a line
2. What do I want to change each time? - the y position and the stroke hue
3. Where does they start, how do they change?- start y at 0, increment by 1- start hue at 0, increment by ???
4. How long should it repeat?- as long as y is less than the canvas height
CS105 | 05 Loops 47
rainbow
CS105 | 05 Loops 48
ideas:
1. [RESTRICTIVE] size(360, 100);
2. [HACK] colorMode(HSB, height, 100, 100);
3. [GOOD] start hue at 0,
increment so hue = 360 when y = height
4. [BEST] express hue as a “function of y”
float vs. int,
using float() conversion function or making
constant values a float with .0
Remapping
CS105 | 05 Loops 49
y-
height
y
Remapping Different Scales
CS105 | 05 Loops 50
height
height - margin
y
0° 360°
marginyStart = margin
yStop = height - margin
rainbow
CS105 | 05 Loops 51
draw rainbow with top and bottom margin
Remapping Different Scales
CS105 | 05 Loops 52
height
height - margin
y
100° 200°
marginyStart = margin
yStop = height -margin
value2 = map(value1, start1, stop1, start2, stop2)
value1 the incoming value to be converted
start1 lower bound of the value's current range
stop1 upper bound of the value's current range
start2 lower bound of the value's target range
stop2 upper bound of the value's target range
CS105 | 05 Loops 53
rainbow_map
CS105 | 05 Loops 54
remap variable using map()
variables for y range and hue range:
current range: yStart to yStop
target range: hueStart to hueStart
float hue = map(y, yStart, yStop,
hueStart, hueStop);
rainbow_interactive
CS105 | 05 Loops 55
use map to adjust
start and stop
colours based on
mouseY
nested conditional
show interactive
feedback
use keys to change
margin
(demos)
CS105 | 05 Loops 56
creating an infinite loop:typical causes:
• forgetting to change the counter variable
• changing the counter variable incorrectly
• using wrong test
an infinite loop is a logical error
precision
CS105 | 05 Loops 57
float a = 0;
void setup() {
frameRate(2);
}
void draw() {
a += 0.1;
if (a == 5) {
background(255, 0, 0);
}
// watch the console output!
println(a);
}
(from "04 Conditionals")
infinite loop due to float precision
CS105 | 05 Loops 58
float a = 0;
void setup() {
frameRate(2);
}
void draw() {
// infinite loop
while (a != 5) {
// watch the console output!
println(a);
a += 0.1;
}
}
when to use int? when to use float?
§ use int to count things (e.g. loop 10 times)
§ use int to “index” things (e.g. array positions)
§ use int if you want to check for equality (e.g. i == 10)
§ use int if you don’t care about decimals (e.g. pixel position)
§ otherwise use float …
CS105 | 05 Loops 59
What does this code output?
CS105 | 05 Loops 60
void setup() {
int i = 0;
for (int y = 0; y < 2; y++) {
i = i + 1;
}
for (int x = 0; x < 3; x++) {
i = i + 1;
}
print(i);
}
spraypaint
CS105 | 05 Loops 61
// draw many dots around the cursor
stroke(0, 10);
strokeWeight(1);
// typical "counting" loop
for (int i = 0; i < dots; i++) {
// local variables to make code easier to read
int x = mouseX + int(random(-spread, spread));
int y = mouseY + int(random(-spread, spread));
point(x, y);
}
hittest_loop
CS105 | 05 Loops 62
int x = 0;
while (x + size < width) {
// the hit test
if (mouseX >= x && mouseX <= x + size &&
mouseY >= y && mouseY <= y + size) {
fill(#ff0000); // red
} else {
fill(255);
}
// draw the rectangle at the current position
rect(x, y, size, size);
x += size;
}
Nested Loop
CS105 | 05 Loops 63
outer code block inner code block
nestedloop
CS105 | 05 Loops 64
int a = 0; // count the cells
int s = 25; // size of each cell
// row
for (int i = 0; i < 4; i++) {
// column
for (int j = 0; j < 3; j++) {
// calculate coordinates based on cell
int x = i * s;
int y = j * s;
// draw something
point(x, y);
text(a, x, y);
a = a + 1;
}
}
Tracethrough
§ tracethrough using the Processing debugger
CS105 | 05 Loops 65
Nested Loop Clock Analogy
CS105 | 05 Loops 66
for (int h = 0; h < 24; h++) {
}
for (int m = 0; m < 60; m++) {
}
for (int s = 0; s < 60; s++ ) {
println(h, m, s);
}
nestedloop_columns
CS105 | 05 Loops
void setup() {
size(300, 300);
colorMode(HSB, 360, 100, 100, 100);
}
void draw() {
// row
for (int x = 0; x < width; x += 20) {
// pick a hue for the column
float hue = map(x, 0, width, 360, 0);
// column
for (int y = 0; y <= height; y += 40) {
fill(hue, 80, 80);
rect(x, y, 20, 40);
}
}
}
67
nestedloop_rows
CS105 | 05 Loops
// nested loop coloured rows
void setup() {
size(300, 300);
colorMode(HSB, 360, 100, 100, 100);
}
void draw() {
// column
for (int y = 0; y <= height; y += 40) {
// pick a hue for the row
float hue = map(y, 0, height, 360, 0);
// row
for (int x = 0; x < width; x += 20) {
fill(hue, 80, 80);
rect(x, y, 20, 40);
}
}
}
68
What does this code output?
CS105 | 05 Loops 69
void setup() {
int i = 0;
for (int y = 0; y < 2; y++) {
for (int x = 0; x < 3; x++) {
i++;
}
}
print(i);
}
hittest_nestedloop
CS105 | 05 Loops 70
using two while loops
randomnestedloop
CS105 | 05 Loops 71
random number of loop iterations
int conversion example
loop from bottom of canvas to top
more map() examples