EARTH 801
Computation and Visualization in the Earth Sciences

Lesson 2: Further examples of for loops II

PrintPrint

The Test

Here's what for loops look like when the only difference between them is the test.

// for loop to demonstrate negative increments

size(400,150);
pixelDensity(2); //makes prettier circles on a retina display
int y = 20; //set the vertical position

//this for loop makes a row of evenly-spaced circles
for (int i =0; i< 200; i=i+50){ 
ellipse(i,y,20,20);
}

y=40; //shift the vertical position down

//this for loop makes a row of circles but ends in a different place
for (int i=0; i<=200; i=i+50){
  ellipse(i,y,20,20);
}

y=60; //shift the vertical position down some more
//this for loop makes a row of circles but ends in a different place
for (int i=0; i<=300; i=i+50){
  ellipse(i,y,20,20);
}

y=80; //shift the vertical position down some more
//what if the initialization and test are the same
for (int i=0; i<=0; i=i+50){
  ellipse(i,y,20,20);
}

y=100; //shift the vertical position down some more
//won't plot any circles because the test immediately fails
for (int i=0; i<0; i=i+50){
  ellipse(i,y,20,20);
}
screenshot of program output demonstrating changes in the test part of a for loop, see text below
Screenshot of the output of program above with 5 loops. Demonstrates different ways the "test" part of the loop affects the output.
program by E. Richardson in Processing

The program above has 5 loops. The first one draws four circles, with origins at (0,20), (50,20), (100,20), and (150,20). It does not draw a circle at x = 200 because the test says to execute the loop only in cases where the increment variable is less than 200. The second loop does draw a circle at (200,40) because the the test says to execute the loop in cases where the increment variable is less than or equal to 200. The third loop draws a couple more circles because the test says to execute up to and including 300. The fourth loop has the initialization variable exactly equal to the test, so the loop executes once and then stops. (No need to write a loop in this case, and the increment doesn't even matter here. It's just for demonstration purposes.)

The 5th loop doesn't plot anything because the initialization variable fails the test right off the bat. So the loop doesn't execute at all. Note that Processing won't give you an error message in a case like this one because nothing you wrote has incorrect syntax. Writing a relational test that always fails is a mental error, but not officially a programming error, so just keep that in mind when troubleshooting your code when you get unexpected results.