In these notes you will learn:
It’s often useful to repeat a set of instructions a given number of times. Let’s say we wanted to sum the numbers from 1 to 100. We could write a long (and tedious) series of statements to do this, like so:
int sum = 1;
sum += 2;
sum += 3;
// ...
sum += 100;
println(sum);
A much better way is to use a for-loop, which is a way to repeat a block of code a given number of times.
In Processing we can use for loops to create interesting shapes made up of multiple similar shapes.
Here is a for loop that sums the numbers from 1 to 100:
int sum = 0;
for(int i=0; i < 100; i++){
sum += i+1;
}
println(sum);
For loop headers always have the same general structure:
Assume that we want to draw a chess board. It should consist of an 8x8 grid of alternating black and white squares. We can break this down into two for loops, one inside the other.
We can think of this as drawing a single row of eight squares and then repeating this process eight times:
void setup() {
size(400, 400);
smooth();
float x = 0;
float y = 0;
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
if (even(row + column)) {
fill(255);
}
else {
fill(0);
}
rect(x, y, 50, 50);
x += 50;
}
x = 0; //move to first column
y += 50; //move to next row
}
}
// Returns true if x is an even number
boolean even(int x) {
return x % 2 == 0;
}
The if statement if (even(row + column)) works out whether a square should be black or white.
And here is an image I drew in Processing that shows this!
In this example we will use a for loop to draw a spiral made up of small circles. The for loop header is a bit more complicated than the previous versions but remember that the same rules apply. Here is the spiral program:
void setup(){
size(200, 200);
smooth();
spiral(100, 100, 6);
}
void spiral(float cx, float cy, float cycles) {
noStroke();
float radius = 1;
for (int deg = 0; deg < 360*cycles; deg += 11) {
float angle = radians(deg);
float x = cx + cos(angle) * radius;
float y = cy + sin(angle) * radius;
ellipse(x, y, 6, 6);
radius = radius + 0.34;
}
}
And this is what the program draws:
This program uses the Polar Coordinates of each circle to calculate the {x, y} coordinates.