int w = 15
int h = 10;
rect(0,10,w,h);
rect(20,10,w,h);
rect(40,10,w,h);
rect(60,10,w,h);
rect(80,10,w,h);
One way to repeat rectangle shapes is to simply repeat the code.
However, this could get very cumbersome if we wanted a lot of rectangles!
size(100,100);
int w = 10;
int h = 50;
for (int i=0; i < 6; i++) {
rect(15*i,0, w, h);
}
Instead, we use a structure called a loop. One type of loop is called a
for-loop.
An example is shown here on the left.
The body of the for-loop is repeated 6 times with the "loop-variable" i changing from 0 to 5. Recall that the
syntax for a rectangle is rect(x,y,w,h) where x is the x-coordinate of the upper left corner.
In this loop the x-coordinate changes from
0*15, 1*15,... 5*15
resulting in a row of rectangles.
The variable i can be used to change any other characteristic you want. See below for more examples.
noFill();
for (int i=0; i < 10; i++) {
rect(0,0, i*10, i*10);
}
for (int i=10; i >= 0; i--) {
fill(i*25,0,255);
rect(0,0, i*10, i*10);
}
background(0,0,0);
for (int i=10; i >= 0; i--) {
stroke(i*25,255,0);
line(0,0, 100-i*10, i*10);
ellipse(100-i*10, i*10,10,10);
}