Home‎ > ‎Unit 03‎ > ‎

For Loop

Computers are really good at repetition. So far you've have to do all the thinking and the copying and pasting of code if you want to do something over and over again. Pages 42-48 of Getting Started with Processing introduce a really cool idea. Watch the video, try the code below and then work through all the examples in the book.
Try this code:
size (100,100);
smooth ();
line(0,0,0,height);
line(0,10,10,height);
line(0,20,20,height);
line(0,30,30,height);
line(0,40,40,height);
line(0,50,50,height);
line(0,60,60,height);
line(0,70,70,height);
line(0,80,80,height);
line(0,90,90,height);
line(0,100,100,height); 


New Code:
size (100,100);
smooth ();
for (int i=0; i<width; i+=10)
{
line(0,i,i,height);
} 

The "for" process above will draw lines that are in successively different positions. You'll notice " int i=0" in the for statement. In this case i only has meaning inside the for loop. This relates to variable and scope. We'll cover scope in the next unit. Play with this code and make some cool pictures.

The basic structure of "for" is as follows:
 Initialize the Process
 Set the Condition
 Expression
 int i=0
 i < width
 i+=10

Assignment 3.3: Elaborate on my program by drawing more than one line in the for loop. Create an image inspired by the one to the right. Be sure to spruce it up a bit. Black and grey are pretty boring, add some color as well. Post the image and the code to your log.

Comparison Operators:
You are not limited to greater than or less than in your conditions within a for loop. Below is a list of comparison operators that can be used:

 x==y  x is equal to y
 x!=y  x is not equal to y
 x>y  x is greater than y
 x>=y  x is greater than or equal to y
 x<y  x is less than y
 x<=y  x is less than or equal to y

The operator that is most important to mention is "x is equal to y". The double equals sign is not a typo. A double equal sign is used to ask the question, does x equal y. If I used a single equals sign "x=y" I would be saying set the value of x to be the value of y. This difference is very important.

Work through the examples on pages 42-48 of Getting Started with Processing prior to completing Assignment 3.4.

Assignment 3.4: Take your code from Assignment 3.2 and use it and a for loop to draw multiple copes of your robot.
Comments