lesson two: everything you need to know
DESCRIPTION
Lesson Two: Everything You Need to Know. Chapter 6: Loops Learning Processing Daniel Shiffman Presentation by Donald W. Smith Graphics from text. Lesson Two: Everything You Need to Know. 4: Variables 5: Conditionals 6: Loops The concept of Iteration Two types of loops: While - PowerPoint PPT PresentationTRANSCRIPT
Lesson Two: Everything You Need to KnowChapter 6: Loops
Learning Processing
Daniel Shiffman
Presentation by Donald W. SmithGraphics from text
Learning Processing: Slides by Don Smith 2
Lesson Two: Everything You Need to Know
4: Variables
5: Conditionals
6: LoopsThe concept of Iteration
Two types of loops:While
For
When do we use them?
Iteration in the context of computer graphics
Learning Processing: Slides by Don Smith 3
What is Iteration?Something that repeats
Each ‘iteration’ may do something different
Usually has a defined condition to stop repeating
You have already ‘used’ loopsProcessing calls draw()over and over until you end your program.
Learning Processing: Slides by Don Smith 4
Why use Iteration?Without Iteration:
// No variablesstroke(0);line( 50,60, 50,80);line( 60,60, 60,80);line( 70,60, 70,80);line( 80,60, 80,80);line( 90,60, 90,80);line(100,60,100,80);line(110,60,110,80);line(120,60,120,80);line(130,60,130,80);line(140,60,140,80);line(150,60,150,80);
Learning Processing: Slides by Don Smith 5
Why use Iteration?Without Iteration:
// No variablesstroke(0);line( 50,60, 50,80);line( 60,60, 60,80);line( 70,60, 70,80);line( 80,60, 80,80);line( 90,60, 90,80);line(100,60,100,80);line(110,60,110,80);line(120,60,120,80);line(130,60,130,80);line(140,60,140,80);line(150,60,150,80);
Study what changesx’s increase each time
What is the pattern?
Add 10 each time
When does it stop?
Last line is at x = 150
Learning Processing: Slides by Don Smith 6
Planning Iteration (Step 1)Without Iteration:
// With x variableint x = 50; int spacing = 10; int len = 20;
line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);..
// No variablesstroke(0);line( 50,60, 50,80);line( 60,60, 60,80);line( 70,60, 70,80);line( 80,60, 80,80);line( 90,60, 90,80);line(100,60,100,80);line(110,60,110,80);line(120,60,120,80);line(130,60,130,80);line(140,60,140,80);line(150,60,150,80);
Learning Processing: Slides by Don Smith 7
Planning Iteration (2)Find the repetitive code
// With x variableint x = 50; int spacing = 10; int len = 20;
line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);..
Learning Processing: Slides by Don Smith 8
Planning Iteration (3)Plan the ‘exit’ condition
When to stop drawing linesx == 150?
x > 150?
x < 150?
x <= 150?
x >= 150?
// With x variableint x = 50; int spacing = 10; int len = 20;
line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);..
Learning Processing: Slides by Don Smith 9
The only Loop You Really Need: whileUse a Boolean Expression to test if we are done
Just like in if-else
There are there other types loops available:[do-]while
for
Action(s)Condition
True
False
Learning Processing: Slides by Don Smith 10
How to plan a loop:Three Parts in every loop:
Setup variables
Loop condition
Actions (loop body) including
the update of loop condition
Make sure the loop will end!The condition should be false at some point…
Or you have an ‘infinite’ loop! (not good)
Action(s)Change test
variable
TestCondition
True
False
Setup
Learning Processing: Slides by Don Smith 11
Infinite loops
Forgetting to update the loop condition usually results in an infinite loopSometimes an infinite loop is needed
Graphical program is polling user input
Operating systems poll user input
many other operations.
Learning Processing: Slides by Don Smith 12
Legs using Iteration
Use the same ‘setup’
Put the repetitive code inside the loop
Put your exit condition in the ‘test’
// Loop Versionint x = 50; int spacing = 10; int endLegs = 150;
while(x < endLegs) { line(x,60,x,80); x = x + spacing;}
// With x variableint x = 50; int spacing = 10; int len = 20;
line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);x = x + spacing;line(x,60,x,80);..
Learning Processing: Slides by Don Smith 13
Three Parts of the LoopFind the three parts:
Setup
Test
Change
// Loop Versionint x = 50; int spacing = 10; int endLegs = 150;
while(x < endLegs) { line(x,60,x,80);
x = x + spacing;}
Learning Processing: Slides by Don Smith 14
Other Examples
Find the sum of the first 100 integers
Setup
Test condition
Update loop condition
Find the sum of the first 50 even (odd) numbers.
Find the average of the first 100 integers
int x = 1; int sum = 0;
while(x < 100) { sum = sum + x;
x = x + 1;}
Let’s see if we can plan and write a loop…
Learning Processing: Slides by Don Smith 15
Look at Figure 6.5
Use 200 x 200 grid
What changes per bar?
Plan the three parts:Setup (initial condition)
Initial y (top bar) ___
Last y: ________
Test (when to stop)
___________
Change
How far apart are bars?
___________
Plan the width tooHow wide are they? _____
Where to start? x = _____
Note: x doesn’t change!
Graph Paper to the Rescue!
Learning Processing: Slides by Don Smith 16
50 60 70
5
10
20
30
40
50
And the code for the loop ‘falls out’…
Learning Processing: Slides by Don Smith 17
void setup() {
size(200,200);
background(255);
fill(125);
}
void draw() {
int y = 5;
int last = height;
while(y < last) {
rect(50,y,100,10);
y = y + 20;
}
}
Exercise 6.1:
Learning Processing: Slides by Don Smith 18
Exit Conditions: When to stop!
How do we know when to stop?Test is usually based on a comparison with a variable
Until age is 21
While changeCount is greater than 5
While not done
Until hitSomething is true
While dayOfMonth is less than daysInMonth
What if we don’t stop?You probably forgot to change the test variable!
Or you changed it in the wrong direction
You have written an ‘infinite’ loop
Not good. Must ‘kill’ processing to get out!
Learning Processing: Slides by Don Smith 19
Learning Processing: Slides by Don Smith 20
Your next loop: for
Use a for loop when: 1) Your ‘test’ variable is a number
2) You know when to stop before you start
Put all three parts on one line:
for(Setup variables; Test Condition;Change test variable){
// Action(s) go here
}
Action(s)Change test
variable
TestCondition
True
False
Setup
Learning Processing: Slides by Don Smith 21
for loop Syntax and Example
Use two semicolons (;) as separators:
for(Setup variables; Test Condition ;Change test variable){
for( int x = 1; x < 10 ; x = x + 1) {
// Action(s) go here
}
Who came up with this?Programmers of course
Why?It saves typing, and it puts all three parts on one line
Exercise 6.2: While to for loop
Learning Processing: Slides by Don Smith 22
Exercise 6-3Wuzzit Do?
Learning Processing: Slides by Don Smith 23
for (int i = 0; i < 10; i++) {
rect(i*20,height/2, 5, 5);
}
for (int i = 0; i < 10; i++) {
rect(i*20,height/2, 5, 5);
}
int i = 0;
while (i < 10) {
ellipse(width/2,height/2, i*10, i*20);
i++;
}
int i = 0;
while (i < 10) {
ellipse(width/2,height/2, i*10, i*20);
i++;
} for (float i = 1.0; i < width; i *= 1.1) {
rect(0,i,i,i*2);
}
for (float i = 1.0; i < width; i *= 1.1) {
rect(0,i,i,i*2);
}
int x = 0;
for (int c = 255; c > 0; c –= 15) {
fill(c);
rect(x,height/2,10,10);
x = x + 10;
}
int x = 0;
for (int c = 255; c > 0; c –= 15) {
fill(c);
rect(x,height/2,10,10);
x = x + 10;
}
Example 6-4
// Global " count "
int count = 0;
void setup() {
size(200,200);
}
void draw() {
count = count + 1;
background(count);
}
________
Learning Processing: Slides by Don Smith 24
// Local " count "
void setup() {
size(200,200);
}
void draw() {
int count = 0;
count = count + 1;
background(count);
}
________
// Local " count "
void setup() {
size(200,200);
}
void draw() {
int count = 0;
count = count + 1;
background(count);
}
________
Global versus Local variables in loops
Which will these produce? A, B or C?
Learning Processing: Slides by Don Smith 25
for Loop Variable ‘Block Scope’
for( int x = 1; x < 10; x = x + 1) {
// steps to do inside the loop
// You can use ‘x’ anywhere in this box
}
if (x > 100) // but x is gone now!
Scope is the ‘lifetime’ of a variable.
When ‘x’is declared in the for statement:‘x’ exists only inside the ‘block’ of the for loop { }
Do you have to declare x inside the for loop? NOint x; // Declare before loop starts (local scope)
for( x = 1; x < 10; x = x + 1) { // assign here
Loop Inside the Main Loop
Remember that draw()is called in a ‘loop’This is often called the ‘main’ loop
The last thing that draw()does is.. .(remember Chapter 1?) ….. Paints the screen
How could you make a set of parallel horizontal lines on the screen?
Learning Processing: Slides by Don Smith 26
Exercise 6.5Render one line at a time inside a for loop:
Until the reach the bottom
Learning Processing: Slides by Don Smith 27
Marching Lines PlanUse a global variable to remember where on the Y axis to start each time (between 1 and 20)
0, 1, 2, 3…. 19, 0, 1, 2, 3…
Initialize it 0
Every time through draw()1) Clear the screen
2) Draw a set of parallel lines (20 pixels apart)Starting at the Y axis where the global variable tells us to
Add 20 to the Y axis each time through
Loop until Y is >= the height of the screen
3) Increment the global variable by 1If it reaches 20, set it back to 0
Learning Processing: Slides by Don Smith 28
Shutters Plan (what changed?)Use a global variable to remember where on the Y axis to start each time (between 1 and 20)
0, 1, 2, 3…. 19, 0, 1, 2, 3…
Initialize it 0
Every time through draw()1) Draw a set of parallel lines (20 pixels apart)
Starting at Y axis where the global variable tells us to
Add 20 to the Y axis each time through
Loop until Y is >= the height of the screen
2) Increment the global variable by 1If it reaches 20, set it back to 0 and…
Clear the screen
Learning Processing: Slides by Don Smith 29
Increment and Decrement Operators
Learning Processing: Slides by Don Smith 30
Loops often use a counter and increment or decrement it as they go.Here is a a “shortcut” way to decrement or increment a variable:
increment operator++x; // increments x by one – BEFORE it is usedx++; // increments x by one – AFTER it is used
decrement operator--x; // decrements x by one – BEFORE it is usedx--; // decrements x by one – AFTER it is used
• When these operators are used as part of an expression, then the choice of pre versus post will make a difference.
How to measure distance between pointsTake one axis (X) for example:
float distance = abs(mouseX – i);
abs() function returns a positive numberAbsolute value… remember algebra!
Used in example 6.9
Exercise 6.6:Rewrite 6.9 using a for loop
Learning Processing: Slides by Don Smith 31
Learning Processing: Slides by Don Smith 32
SummaryIteration (looping) is another way to control the flowEvery loop must have three elements:
1) Initialization (of something to count or test)2) Test if you are done yet3) Update the test variable
The ‘while’ loop can do everything you needInitialize before the test, test up front, don’t forget to update!
A ‘for’ loop puts all three elements on one lineA variable’s ‘scope’ can be:
Global, Local to the method, or inside a block of code { }
Increment (++) or decrement (--) operators save typing!You can use print() and println() to help debug your programs while you are developing them