Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 2: Variables and Loops

[gn_pullquote align="left"]A variable stores a value in memory so that it can be used later in a program. The variable can be used many times within a single program, and the value is easily changed while the program is running.[/gn_pullquote] Variables

We use variables to avoid repeating ourselves in code. If you’re typing the same number more than once, consider making it into a variable, so that it is easier to debug and easier to update. Values that are stored into variables can be changed throughout the code and can be assigned new values, whatever their value originally was. This is extremely useful.

For instance, when you make the y-coordinate and diameter for the two circles in this example into variables, the same values are used for each ellipse:

size(480, 120);
smooth();
int y = 60;
int d = 80;
ellipse(75, y, d, d);   // Left
ellipse(175, y, d, d);  // Middle
ellipse(275, y, d, d);  // Right

By simply changing the y and d variables, we can affect all three shapes. The variable’s value will change at every instance it appears, by only altering two lines of code:

size(480, 120);
smooth();
int y = 100;
int d = 130;
ellipse(75, y, d, d);   // Left
ellipse(175, y, d, d);  // Middle
ellipse(275, y, d, d);  // Right

 

When making variables, you determine the name, the data type, and the value. It’s wise to choose names that are unique, and which cleary identify the variable’s role or function. Also, keeping names consistent will keep code more readable. The convention I use is to begin with a lower case, and capitalize each subsequent word with a capital, for instance, variableName. Generally, I name my variables consistently in this way.

A variable’s data type defines the range of the variable. Common data types are integer (which stores a whole number, positive or negative), float (which stores a decimal), char (for storing characters), and so on. You can read more about data types by reading the reference and by scrolling down to Data. Data types are standard across many programming languages, and sometimes you’ll need to convert between data types, so it’s a good idea to be familiar with them.

Before you can use a variable, you need to declare it, so your compiler knows to expect it later in the program, by setting aside space in the computer’s memory to store the information for later. You do this by assigning a data type and name, and an optional initial value (which, remember, can be changed later on if you choose).

1
int x = 12;  // Declare x as an int variable and assign it a value of 12

There are variables built into Processing which store special information about your program. Two of these are width and height, which are stored inside the size() function. These are very useful, because they can be used to reference elements relative to the size of the window, even if the size() line changes.

Operators

in code, symbols like +, -, and * are called operators. When placed between values, they create an expression. The operators follow the basic order of operations (PEMDAS). There are shortcuts for the most common operations, for instance:

1
x += 10;  // This is the same as x = x + 10;
1
y *= -1;  // This is the same as y = y * -1;

Addiitonally, it is often the case that you’ll want to increment (count up by one) or decrement (count down by one), and there are shortcuts for this, as well:

1
x ++;  // This is the same as x = x + 1;
1
y --;  // This is the same as y = y - 1;

You’ll find more shortcuts under the Operators section of the reference.

Loops

[gn_pullquote align="left"]The ultimate power of working with a for loop is the ability to make quick changes to the code.[/gn_pullquote]

Take a look at the two codes below. Both will yield the same result. You’ll see that a for() loop will significantly cut down the amount of code you have to write, and help minimize the chances that you might make a mistake. Also, Because the code inside the block is typically run multiple times, a change to the block is magnified when the code is run.

 
Without Loop

size(400, 120); 
smooth(); 
strokeweight(8); 
line(20, 40, 80, 80); 
line(80, 40, 140, 80); 
line(140, 40, 200, 80); 
line(200, 40, 260, 80); 
line(260, 40, 320, 80); 
line(320, 40, 380, 80); 
line(380, 40, 440, 80);


With Loop

size(400, 120);
smooth();
strokeweight(8);
for (int i = 20; i < 400; i += 60) {
  line(i, 40, i + 60, 80);
}

 

The for() loop is different from what we’ve written so far. Note the curly braces. Also note the three statements, separated by semicolons, inside the parentheses.

for (init; test; update) {
  statements
}

 

The word init refers to the initialization, and it declares a new variable to use within the for() loop and assigns a value. In this case, the letter i is arbitrary, but it is often used. The test evaluates the value of this variable, and if it meets the conditions, the loop carries out the third statement and updates its value. The loop will continue so long as the second condition is satisfied, and once it is no longer satisfied, the code breaks out of the loop and continues on.

Look what happens when we modify the previous example even slightly:

size(480, 120);
smooth();
strokeWeight(2);
for (int i = 20; i < 400; i += 8) {
  line(i, 40, i + 60, 80);
}

When one for loop is embedded inside another, the number of repetitions is multiplied. These are called nested loops.

size(480, 120);
background(0);
smooth();
noStroke();
for (int y = 0; y <= height; y += 40) {
  for (int x = 0; x <= width; x += 40) {
    fill(255, 140);
    ellipse(x, y, 40, 40);
  }
}

In this example, the y variable is set to increment by 40, up until and equal to the height of the window (which is set to 120). This means the loop will iterate 4 times. Similarly, the inner loop 13 times. Once the inner loop is finished iterating, it will break out into the outer loop, which will increment by 40, and then push back into the inner loop for another 13 iterations. The inner loop iterates 13 times for one of every 4 of the outer loop’s iterations, for a total of 52 iterations. You can easily see how nested loops grow in magnitude and add many layers of depth to your code.