For Loops :P
Ft. Catherine, Nicole, Julia and Maria
Agenda for Today
What are for loops, and how do they work?
Syntax (pt. 1)
Writing a for loop:
for (int i = 1; i < 3; i ++) {
println (i);
}
1
2
counts how many times the action executes by declaring and incrementing a variable
the repeated action
(initial value, testing condition, increment)
Syntax (pt. 2)
Other variables can also be declared in the first portion of the loop
The counter variable can also be declared outside the loop
sets the variable to a random integer from 0 to 4
Output:
inside: 0
inside: 1
inside: 2
inside: 3
inside: 4
inside: 5
outside: 6
Possible Errors
A for loop that never runs:
A for loop that runs infinitely:
the initial value already does not meet the conditions (i<=25), so the loop never runs
value for i will always meet the conditions (i>=25)
Applications
Draws 12 stripes
Draws a filled 50x50 ellipse
Challenge Problem 1
From a range of two numbers (inclusive), can you find the sum of all the perfect squares within the range?
ex. 2 to 9 gives 284 (4 + 9 + 16 + 25 + 36 + 49 + 64 + 81)
Challenge Problem 2
Create a vertical gradient from white to black on the default 800x500 screen
(Top is white, bottom is black)