EARTH 801
Computation and Visualization in the Earth Sciences

Lesson 2: Further examples of for loops I

PrintPrint

Initialization

Here's what it looks like when you write two for loops and the only difference between them is the initialization variable:
 

// for loop to demonstrate changing the initialization

size(400,100);
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< 400; i=i+50){
	ellipse(i,y,20,20);
	}

y=40; //shift the vertical position down

//this for loop makes the same row of circles but shifted over
//by 10 pixels because we changed the initialization variable
for (int i=10; i<400; i=i+50){
	  ellipse(i,y,20,20);
	}
screenshot of program in which for loop initial variable is changed
Screenshot of program output in which two for loops differ only by their initial variable
program written by E. Richardson in Processing

The top line of circles were placed by starting at a horizontal position of zero, and a vertical position of 20. Then the horizontal position in increased by 50 and the vertical position is unchanged, and another same-sized circle is drawn. Then the horizontal position is increased by 50 more, the vertical position is unchanged, and another same-sized circle is drawn. This goes on until we reach a horizontal position of 400.

The loop says:

for (int i =0; i< 400; i=i+50){

	ellipse(i,20,20,20);

	}

That first loop is the equivalent of:

ellipse(0,20,20,20)

ellipse(50,20,20,20);

ellipse(100,20,20,20);

ellipse(150,20,20,20);

ellipse(200,20,20,20);

ellipse(250,20,20,20);

ellipse(300,20,20,20);

ellipse(350,20,20,20);

See how much typing you save with a loop, and also the chance of making an error is less because the computer is doing the computation for you.

The second loop in the program only differs from the first one in the initialization variable (and we shifted the vertical position down so we could see both sets of circles more easily). The second loop says:

for (int i =10; i< 400; i=i+50){

	ellipse(i,40,20,20);

	}

That second loop is the equivalent of:

ellipse(10,40,20,20)

ellipse(60,40,20,20);

ellipse(110,40,20,20);

ellipse(160,40,20,20);

ellipse(210,40,20,20);

ellipse(260,40,20,20);

ellipse(310,40,20,20);

ellipse(360,40,20,20);

Again, this would be a long program if we had set each of these circles by hand. Rule of thumb: If you find yourself typing a few commands in a row that look very repetitive, then a loop is probably a good idea. Note that when you are constructing a program, sometimes you don't start out realizing you want a loop until you notice that you've just typed a bunch of repetitive commands.