4.1 What is a Variable?
The computer has memory. Why do we call it memory? Because it is what the computer uses to remember stuff it needs.
Technically speaking, a variable is a named pointer to a location in the computer’s memory ( “memory address ” ) where data is stored. Since computers only process information one instruction at a time, a variable allows a programmer to save information from one point in the program and refer back to it at a later time. For a Processing programmer, this is incredibly useful; variables can keep track of information related to shapes: color, size, location. Variables are exactly what you need to make a triangle change from
blue to purple, a circle fly across the screen, and a rectangle shrink into oblivion.
Out of all the available analogies, I tend to prefer the piece of paper approach: graph paper .
Imagine that the computer’s memory is a sheet of graph paper and each cell on the graph paper has an address. With pixels, we learned how to refer to those cells by column and row numbers. Wouldn’t it be nice if we could name those cells? With variables, we can.
The computer has memory. Why do we call it memory? Because it is what the computer uses to remember stuff it needs.
Technically speaking, a variable is a named pointer to a location in the computer’s memory ( “memory address ” ) where data is stored. Since computers only process information one instruction at a time, a variable allows a programmer to save information from one point in the program and refer back to it at a later time. For a Processing programmer, this is incredibly useful; variables can keep track of information related to shapes: color, size, location. Variables are exactly what you need to make a triangle change from
blue to purple, a circle fly across the screen, and a rectangle shrink into oblivion.
Out of all the available analogies, I tend to prefer the piece of paper approach: graph paper .
Imagine that the computer’s memory is a sheet of graph paper and each cell on the graph paper has an address. With pixels, we learned how to refer to those cells by column and row numbers. Wouldn’t it be nice if we could name those cells? With variables, we can.
Let’s name one “ Billy’s Score ” (we will see why we are calling
it that in the next section) and give it the value 100. That way, whenever we want to use Billy’s score in a program, we do not have to remember the value 100. It is there in memory and we can ask for it by name. See Figure 4.2 . The power of a variable does not simply rest with the ability to remember a value. The whole point of a variable is that those values vary, and more interesting situations arise as we periodically alter that value. Consider a game of Scrabble between Billy and Jane. To keep track of the score, Jane takes out paper and pencil, and scrawls down two column names: “ Billy’s Score ” and “ Jane’s Score. ” As the two play, a running tally is kept of each player’s points below the headings. If we imagine this game to be virtual Scrabble programmed on a computer, we suddenly can see the concept of a variable that varies emerge. That piece of paper is the computer’s memory and on that paper, information is written— “ Billy’s Score ” and “ Jane’s Score ” are variables, locations in memory where each player’s total points are stored and that change over time. See Figure 4.3 . |
4.2 Variable Declaration and Initialization
Variables can hold primitive values or references to objects and arrays . For now, we are just going to worry about primitives—we will get to objects and arrays later. Primitive values are the building blocks of data on the computer and typically involve a singular
piece of information, like a number or character.
Variables are declared by first stating the type, followed by the name. Variable names must be one word (no spaces) and must start with a letter (they can include numbers, but cannot start with a number). They cannot include any punctuation or special characters, with the exception of the underscore: “_” .
A type is the kind of data stored in that variable. This could be a whole number, a decimal number, or a character. Here are data types you will commonly use:
• Whole numbers, such as 0, 1, 2, 3, -1, -2, and so on are stored as “integers ” and the type keyword for integer is “ int ” .
• Decimal numbers, such as 3.14159, 2.5, and –9.95 are typically stored as “ floating point values ” and the type keyword for floating point is “ float ”.
• Characters, such as the letters ‘ a ’ , ‘b ’ , ‘ c ’ , and so on are stored in variables of type “ char ” and are declared as a letter enclosed in single quotes, that is, ‘ a ’ . Characters are useful when determining what letter on the keyboard has been pressed, and for other uses involving Strings of text
Don’t Forget
• Variables must have a type. Why? This is how the computer knows exactly how much memory should be allocated to store that variable’s data.
• Variables must have a name.
All Primitive Types
• boolean : true or false
• char : a character, ‘ a ’ ,‘b ’ ,‘c ’ , etc.
• byte : a small number, –128 to 127
• short : a larger number, –32768 to 32767
• int : a big number, –2147483648 to 2147483647
• long : a really huge number
• float : a decimal number , such as 3.14159
• double : a decimal number with a lot more decimal places (only necessary for advanced programs requiring mathematical precision).
Once a variable is declared, we can then assign it a value by setting it equal to something. In most cases, if we forget to initialize a variable, Processing will give it a default value, such as 0 for integers, 0.0 for floating points, and so on. However, it is good to get into the habit of always initializing variables in order to avoid confusion.
You initialize variables as the first lines of your code (BEFORE DRAW AND SETUP) and by one of the following ways:
int count;
count = 50; \\This initializes the variable "count" as an integer and sets the value to 50. This is over two lines.
Another way:
int count = 50; \\This does the same as above but only uses one line (THE WAY I PREFER!)
What’s in a name? Tips for choosing good variable names
• Avoid using words that appear elsewhere in the Processing language. In other words, do not call your variable mouseX , there already is one!
• Use names that mean something. This may seem obvious, but it is an important point. For example, if you are using a variable to keep track of score, call it “ score ” and not, say, “ cat. ”
• Start your variable with a lowercase letter and join together words with capitals. Words that start with capitals are reserved for classes (Chapter 8). For example: “ frogColor ” is good, “ Frogcolor ” is not. this canTake some gettingUsedTo but it will comeNaturally soonEnough.
A variable can also be initialized by another variable ( x equals y ), or by evaluating a mathematical expression ( x equals y plus z , etc.). Here are some examples:
When should you use a variable?
Some programmers say that if a number appears three or more times, it should be a variable. Personally, I would say if a number appears once, use a variable. Always use variables!
Example 4-1: Variable declaration and initialization examples
int count = 0; // Declare an int named count, assigned the value 0
char letter = ' a'; // Declare a char named letter, assigned the value 'a'
double d = 132.32; // Declare a double named d, assigned the value 132.32
boolean happy = false; // Declare a boolean named happy, assigned the value false
float x = 4.0; // Declare a float named x, assigned the value 4.0
float y; // Declare a float named y (no assignment)
y = x + 5.2; // Assign the value of x plus 5.2 to the previously declared y
float z = x *y + 15.0; // Declare a variable named z, assign it the value which
// is x times y plus 15.0.
Variables can hold primitive values or references to objects and arrays . For now, we are just going to worry about primitives—we will get to objects and arrays later. Primitive values are the building blocks of data on the computer and typically involve a singular
piece of information, like a number or character.
Variables are declared by first stating the type, followed by the name. Variable names must be one word (no spaces) and must start with a letter (they can include numbers, but cannot start with a number). They cannot include any punctuation or special characters, with the exception of the underscore: “_” .
A type is the kind of data stored in that variable. This could be a whole number, a decimal number, or a character. Here are data types you will commonly use:
• Whole numbers, such as 0, 1, 2, 3, -1, -2, and so on are stored as “integers ” and the type keyword for integer is “ int ” .
• Decimal numbers, such as 3.14159, 2.5, and –9.95 are typically stored as “ floating point values ” and the type keyword for floating point is “ float ”.
• Characters, such as the letters ‘ a ’ , ‘b ’ , ‘ c ’ , and so on are stored in variables of type “ char ” and are declared as a letter enclosed in single quotes, that is, ‘ a ’ . Characters are useful when determining what letter on the keyboard has been pressed, and for other uses involving Strings of text
- String, used to create words such as "Mr. Martin".
Don’t Forget
• Variables must have a type. Why? This is how the computer knows exactly how much memory should be allocated to store that variable’s data.
• Variables must have a name.
All Primitive Types
• boolean : true or false
• char : a character, ‘ a ’ ,‘b ’ ,‘c ’ , etc.
• byte : a small number, –128 to 127
• short : a larger number, –32768 to 32767
• int : a big number, –2147483648 to 2147483647
• long : a really huge number
• float : a decimal number , such as 3.14159
• double : a decimal number with a lot more decimal places (only necessary for advanced programs requiring mathematical precision).
Once a variable is declared, we can then assign it a value by setting it equal to something. In most cases, if we forget to initialize a variable, Processing will give it a default value, such as 0 for integers, 0.0 for floating points, and so on. However, it is good to get into the habit of always initializing variables in order to avoid confusion.
You initialize variables as the first lines of your code (BEFORE DRAW AND SETUP) and by one of the following ways:
int count;
count = 50; \\This initializes the variable "count" as an integer and sets the value to 50. This is over two lines.
Another way:
int count = 50; \\This does the same as above but only uses one line (THE WAY I PREFER!)
What’s in a name? Tips for choosing good variable names
• Avoid using words that appear elsewhere in the Processing language. In other words, do not call your variable mouseX , there already is one!
• Use names that mean something. This may seem obvious, but it is an important point. For example, if you are using a variable to keep track of score, call it “ score ” and not, say, “ cat. ”
• Start your variable with a lowercase letter and join together words with capitals. Words that start with capitals are reserved for classes (Chapter 8). For example: “ frogColor ” is good, “ Frogcolor ” is not. this canTake some gettingUsedTo but it will comeNaturally soonEnough.
A variable can also be initialized by another variable ( x equals y ), or by evaluating a mathematical expression ( x equals y plus z , etc.). Here are some examples:
When should you use a variable?
Some programmers say that if a number appears three or more times, it should be a variable. Personally, I would say if a number appears once, use a variable. Always use variables!
Example 4-1: Variable declaration and initialization examples
int count = 0; // Declare an int named count, assigned the value 0
char letter = ' a'; // Declare a char named letter, assigned the value 'a'
double d = 132.32; // Declare a double named d, assigned the value 132.32
boolean happy = false; // Declare a boolean named happy, assigned the value false
float x = 4.0; // Declare a float named x, assigned the value 4.0
float y; // Declare a float named y (no assignment)
y = x + 5.2; // Assign the value of x plus 5.2 to the previously declared y
float z = x *y + 15.0; // Declare a variable named z, assign it the value which
// is x times y plus 15.0.
4.3 Using a Variable
Though it may initially seem more complicated to have words standing in for numbers, variables make our lives easier and more interesting. Let’s take a simple example of a program that draws a circle onscreen.
First without variables:
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(100,100,50,50);
}
Now we have already learned how to use mouseX and mouseY. What we want to do now is create our own variables by following the syntax for declaring and initializing outlined above, placing the variables at the top of our code. You can declare variables elsewhere in your code and we will get into this later. For now to avoid any confusion, all variables should be at the top.
Here is the same code with variables:
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(100);
stroke(255);
fill(0);
ellipse(circleX,circleY,50,50);
}
Running this code, we achieve the same result as in the fi rst example: a circle appears in the middle of the screen. Nevertheless, we should open our hearts and remind ourselves that a variable is not simply a placeholder for one constant value. We call it a variable because it varies . To change its value, we write an assignment operation , which assigns a new value.
Up until now, every single line of code we wrote called a function: line( ), ellipse( ), stroke( ), etc . Variables introduce assignment operations to the mix. Here is what one looks like (it is the same as how we initialize a variable, only the variable does not need to be declared).
variable name =expression
x = 5;
x = a + b;
x = y - 10 * 20;
x = x * 5;
You can also increment a variable:
A common example is incrementation. In the above code, circleX starts with a value of 100. If we want to increment circleX by one, we say circleX equals itself plus one. In code, this amounts to“ circleX = circleX+1; ” .
Let’s try adding that to our program (and let’s start circleX with the value of 0).
Incrementing circle:
int circle X = 0;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(circleX,circleY,50,50);
circleX = circleX + 1;
}
What happens? If you run the example in Processing , you will notice that the circle moves from left to right. Remember, draw( ) loops over and over again, all the while retaining the value of circleX in memory.
Practising how to follow the code step-by-step will lead you to the questions you need to ask before writing your own sketches. Be one with the computer.
Task:
Change the code so that instead of the circle moving from left to right, the circle grows in size. What would you change to have the circle follow the mouse as it grows? How could you vary the speed at which the circle grows? Show an example of an answer to each question.
Here is a "starter code"
int circleSize = 0;
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
fill(175);
____________________________________
____________________________________
}
Though it may initially seem more complicated to have words standing in for numbers, variables make our lives easier and more interesting. Let’s take a simple example of a program that draws a circle onscreen.
First without variables:
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(100,100,50,50);
}
Now we have already learned how to use mouseX and mouseY. What we want to do now is create our own variables by following the syntax for declaring and initializing outlined above, placing the variables at the top of our code. You can declare variables elsewhere in your code and we will get into this later. For now to avoid any confusion, all variables should be at the top.
Here is the same code with variables:
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(100);
stroke(255);
fill(0);
ellipse(circleX,circleY,50,50);
}
Running this code, we achieve the same result as in the fi rst example: a circle appears in the middle of the screen. Nevertheless, we should open our hearts and remind ourselves that a variable is not simply a placeholder for one constant value. We call it a variable because it varies . To change its value, we write an assignment operation , which assigns a new value.
Up until now, every single line of code we wrote called a function: line( ), ellipse( ), stroke( ), etc . Variables introduce assignment operations to the mix. Here is what one looks like (it is the same as how we initialize a variable, only the variable does not need to be declared).
variable name =expression
x = 5;
x = a + b;
x = y - 10 * 20;
x = x * 5;
You can also increment a variable:
A common example is incrementation. In the above code, circleX starts with a value of 100. If we want to increment circleX by one, we say circleX equals itself plus one. In code, this amounts to“ circleX = circleX+1; ” .
Let’s try adding that to our program (and let’s start circleX with the value of 0).
Incrementing circle:
int circle X = 0;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(255);
stroke(0);
fill(175);
ellipse(circleX,circleY,50,50);
circleX = circleX + 1;
}
What happens? If you run the example in Processing , you will notice that the circle moves from left to right. Remember, draw( ) loops over and over again, all the while retaining the value of circleX in memory.
Practising how to follow the code step-by-step will lead you to the questions you need to ask before writing your own sketches. Be one with the computer.
Task:
Change the code so that instead of the circle moving from left to right, the circle grows in size. What would you change to have the circle follow the mouse as it grows? How could you vary the speed at which the circle grows? Show an example of an answer to each question.
Here is a "starter code"
int circleSize = 0;
int circleX = 100;
int circleY = 100;
void setup() {
size(200,200);
}
void draw() {
background(0);
stroke(255);
fill(175);
____________________________________
____________________________________
}
4.4 Many Variables
Let’s take the example one step further and use variables for every piece of information we can think of. We will also use floating point values to demonstrate greater precision in adjusting variable values.
Here is a basic layout of 8 variables (THIS WILL NOT WORK AS CODE AS I HAVE USED THE WORDS "change" to represent any number)
float circleX = 0;
float circleY = 0;
float circleW = 50;
float circleH = 100;
float circleStroke = 255;
float circleFill = 0;
float backgroundColor = 255;
float change = 0.5;
// Your basic setup
void setup() {
size(200,200);
smooth();
}
void draw() {
// Draw the background and the ellipse
background(backgroundColor);
stroke(circleStroke);
fill(circleFill);
ellipse(circleX,circleY,circleW,circleH);
// Change the values of all variables
circleX = circleX + change;
circleY = circleY + change;
circleW = circleW + change;
circleH = circleH - change;
circleStroke = circleStroke - change;
circleFill = circleFill + change;
}
Task:
Step 1 : Write code that draws the following screenshots with hard-coded values. (Feel free to use colors instead of grayscale.)
Step 2 : Replace all of the hard-coded numbers with variables.
Step 3 : Write assignment operations in draw( ) that change the value of the variables. For example, “ variable1 variable1 2; ” . Try different expressions and see what happens!
Let’s take the example one step further and use variables for every piece of information we can think of. We will also use floating point values to demonstrate greater precision in adjusting variable values.
Here is a basic layout of 8 variables (THIS WILL NOT WORK AS CODE AS I HAVE USED THE WORDS "change" to represent any number)
float circleX = 0;
float circleY = 0;
float circleW = 50;
float circleH = 100;
float circleStroke = 255;
float circleFill = 0;
float backgroundColor = 255;
float change = 0.5;
// Your basic setup
void setup() {
size(200,200);
smooth();
}
void draw() {
// Draw the background and the ellipse
background(backgroundColor);
stroke(circleStroke);
fill(circleFill);
ellipse(circleX,circleY,circleW,circleH);
// Change the values of all variables
circleX = circleX + change;
circleY = circleY + change;
circleW = circleW + change;
circleH = circleH - change;
circleStroke = circleStroke - change;
circleFill = circleFill + change;
}
Task:
Step 1 : Write code that draws the following screenshots with hard-coded values. (Feel free to use colors instead of grayscale.)
Step 2 : Replace all of the hard-coded numbers with variables.
Step 3 : Write assignment operations in draw( ) that change the value of the variables. For example, “ variable1 variable1 2; ” . Try different expressions and see what happens!
4.5 System Variables
As we saw with mouseX and mouseY , Processing has a set of convenient system variables freely available. These are commonly needed pieces of data associated with all sketches (such as the width of the window, the key pressed on the keyboard, etc.). When naming your own variables, it is best to avoid system variable names, however, if you inadvertently use one, your variable will become primary and override the system one. Here is a list of commonly used system variables (there are more, which you can find in the
Processing reference).
• width —Width (in pixels) of sketch window.
• height —Height (in pixels) of sketch window.
• frameCount —Number of frames processed.• frameRate —Rate that frames are processed (per second).
• screen.width —Width (in pixels) of entire screen.
• screen.height —Height (in pixels) of entire screen.
• key —Most recent key pressed on the keyboard.
• keyCode —Numeric code for key pressed on keyboard.
• keyPressed —True or false? Is a key pressed?
• mousePressed —True or false? Is the mouse pressed?
• mouseButton —Which button is pressed? Left, right, or center?
Following is an example that makes use of some of the above variables; we are not ready to use them all yet, as we will need some more advanced concepts to make use of many features. TRY IT!
void setup() {
size(200,200);
frameRate(30);
}
void draw() {
background(100);
stroke(255);
fill(frameCount/2);
rectMode(CENTER);
rect(width/2,height/2,mouseX + 10,mouseY + 10);
}
void keyPressed() {
println(key);
}
TASK:
Exercise 4-5: Using width and height, recreate the following screenshot. Here’s the catch: the shapes must resize themselves relative to the window size. (In other words, no matter what you specify for size( ) , the result should look identical.)
As we saw with mouseX and mouseY , Processing has a set of convenient system variables freely available. These are commonly needed pieces of data associated with all sketches (such as the width of the window, the key pressed on the keyboard, etc.). When naming your own variables, it is best to avoid system variable names, however, if you inadvertently use one, your variable will become primary and override the system one. Here is a list of commonly used system variables (there are more, which you can find in the
Processing reference).
• width —Width (in pixels) of sketch window.
• height —Height (in pixels) of sketch window.
• frameCount —Number of frames processed.• frameRate —Rate that frames are processed (per second).
• screen.width —Width (in pixels) of entire screen.
• screen.height —Height (in pixels) of entire screen.
• key —Most recent key pressed on the keyboard.
• keyCode —Numeric code for key pressed on keyboard.
• keyPressed —True or false? Is a key pressed?
• mousePressed —True or false? Is the mouse pressed?
• mouseButton —Which button is pressed? Left, right, or center?
Following is an example that makes use of some of the above variables; we are not ready to use them all yet, as we will need some more advanced concepts to make use of many features. TRY IT!
void setup() {
size(200,200);
frameRate(30);
}
void draw() {
background(100);
stroke(255);
fill(frameCount/2);
rectMode(CENTER);
rect(width/2,height/2,mouseX + 10,mouseY + 10);
}
void keyPressed() {
println(key);
}
TASK:
Exercise 4-5: Using width and height, recreate the following screenshot. Here’s the catch: the shapes must resize themselves relative to the window size. (In other words, no matter what you specify for size( ) , the result should look identical.)
5 Conditionals5.1 Boolean Expressions (THIS IS FOR THE LAST PART OF THE NEXT ASSIGNMENT)
What’s your favorite kind of test? Essay format? Multiple choice? In the world of computer programming, we only take one kind of test: a boolean test—true or false. A boolean expression (named for mathematician George Boole) is an expression that evaluates to either true or false. Let’s look at some common language examples:
• I am hungry. → true
• I am afraid of computer programming. → false
• Mr. Martin is hilarious. → true
In the formal logic of computer science, we test relationships between numbers.
• 15 is greater than 20 → false
• 5 equals 5 → true
• 32 is less than or equal to 33 → true
Now we will learn how to use a variable in a boolean expression, allowing our sketch to take different paths depending on the current value stored in the variable.
• x >20 → depends on current value of x
• y == 5 → depends on current value of y
• z <= 33 → depends on current value of z
The following operators can be used in a boolean expression.
What’s your favorite kind of test? Essay format? Multiple choice? In the world of computer programming, we only take one kind of test: a boolean test—true or false. A boolean expression (named for mathematician George Boole) is an expression that evaluates to either true or false. Let’s look at some common language examples:
• I am hungry. → true
• I am afraid of computer programming. → false
• Mr. Martin is hilarious. → true
In the formal logic of computer science, we test relationships between numbers.
• 15 is greater than 20 → false
• 5 equals 5 → true
• 32 is less than or equal to 33 → true
Now we will learn how to use a variable in a boolean expression, allowing our sketch to take different paths depending on the current value stored in the variable.
• x >20 → depends on current value of x
• y == 5 → depends on current value of y
• z <= 33 → depends on current value of z
The following operators can be used in a boolean expression.
5.2 Conditionals: If, Else, Else If
Boolean expressions (often referred to as “ conditionals ” ) operate within the sketch as questions. Is 15 greater than 20? If the answer is yes (i.e., true), we can choose to execute certain instructions (such as draw a rectangle); if the answer is no (i.e., false), those instructions are ignored. This introduces the idea of branching; depending on various conditions, the program can follow different paths.
In the physical world, this might amount to instructions like so:
If I am hungry then eat some food, otherwise if I am thirsty, drink some water, otherwise, take a nap .
In Processing , we might have something more like:
If the mouse is on the left side of the screen, draw a rectangle on the left side of the screen .
Boolean expressions (often referred to as “ conditionals ” ) operate within the sketch as questions. Is 15 greater than 20? If the answer is yes (i.e., true), we can choose to execute certain instructions (such as draw a rectangle); if the answer is no (i.e., false), those instructions are ignored. This introduces the idea of branching; depending on various conditions, the program can follow different paths.
In the physical world, this might amount to instructions like so:
If I am hungry then eat some food, otherwise if I am thirsty, drink some water, otherwise, take a nap .
In Processing , we might have something more like:
If the mouse is on the left side of the screen, draw a rectangle on the left side of the screen .
Or, more formally, with:
if (mouseX < width/2) {
fill(255);
rect(0,0,width/2,height);
}
How does this work?
The boolean expression and resulting instructions in the above source code is contained within a block of code with the following syntax and structure:
if (boolean expression) {
// code to execute if boolean expression is true
}
The structure can be expanded with the keyword else to include code that is executed if the boolean
expression is false. Th is is the equivalent of “ otherwise, do such and such. ”
if (boolean expression) {
// code to execute if boolean expression is true
} else {
// code to execute if boolean expression is false
}
For example, we could say the following, If the mouse is on the left side of the screen, draw a white background, otherwise draw a black background .
if (mouseX < width/2) {
background(255);
} else {
background(0);
}
if (mouseX < width/2) {
fill(255);
rect(0,0,width/2,height);
}
How does this work?
The boolean expression and resulting instructions in the above source code is contained within a block of code with the following syntax and structure:
if (boolean expression) {
// code to execute if boolean expression is true
}
The structure can be expanded with the keyword else to include code that is executed if the boolean
expression is false. Th is is the equivalent of “ otherwise, do such and such. ”
if (boolean expression) {
// code to execute if boolean expression is true
} else {
// code to execute if boolean expression is false
}
For example, we could say the following, If the mouse is on the left side of the screen, draw a white background, otherwise draw a black background .
if (mouseX < width/2) {
background(255);
} else {
background(0);
}
Finally, for testing multiple conditions, we can employ an “ else if.”
When an else if is used, the conditional statements are evaluated in the order presented. As soon as one boolean expression is found to be true, the corresponding code is executed and the remaining boolean expressions are ignored. See picture to the right if (boolean expression #1) { // code to execute if boolean expression #1 is true } else if (boolean expression #2) { // code to execute if boolean expression #2 is true } else if (boolean expression #n) { // code to execute if boolean expression #n is true } else { // code to execute if none of the above // boolean expressions are true } Taking our simple mouse example a step further, we could say the following: If the mouse is on the left third of the window, draw a white background, if it is in the middle third, draw a gray background, otherwise, draw a black background. if (mouseX < width/3) { background(255); } else if (mouseX < 2*width/3) { background(127); } else { background(0); } |