1 of 9

For Loops :P

Ft. Catherine, Nicole, Julia and Maria

2 of 9

Agenda for Today

  • Attendance
  • What Are For Loops?
  • Syntax
  • Possible Errors
  • Useful Applications
  • Challenge Problems

3 of 9

What are for loops, and how do they work?

  • One of the most essential and commonly used concepts
  • Allow you to execute a segment of code repeatedly for a set number of times
  • Instead of repeating code, you can put it in a for loop to save work (KISS)
  • In a for loop you specify:
    • The starting value
    • The testing condition
    • The increment
  • Each time the code in a for loop is executed, it is called an iteration

4 of 9

Syntax (pt. 1)

Writing a for loop:

for (int i = 1; i < 3; i ++) {

println (i);

}

  • the loop runs starting from 1 and increases by 1 for all integer values less than 3
  • so, the for loop will run for 2 iterations and the output will be:

1

2

counts how many times the action executes by declaring and incrementing a variable

the repeated action

(initial value, testing condition, increment)

5 of 9

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

  • allows it to be used even after the loop has finished running

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

6 of 9

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)

7 of 9

Applications

  • Drawing and Animation
    • Instead of drawing multiples of the same shape in a row�
  • Filling objects
    • change the width/height of the object using the loop counter�

Draws 12 stripes

Draws a filled 50x50 ellipse

  • Applications for math problems
    • Finding prime numbers, perfect squares, factors of a number, etc.
    • (We’ll go over these more in the future)

8 of 9

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)

9 of 9

Challenge Problem 2

Create a vertical gradient from white to black on the default 800x500 screen

(Top is white, bottom is black)