Conditional Statements

This blog post is going to review conditional statements, boolean expressions and logical and relational operators. The latter ones are needed in order to create conditional statements. I will list the most important ones:

<……..smaller than
>..……greater than
<=……smaller or equal to
>=……greater or equal to
==……equal to
!=….…not equal to

They are used in conditional statements because they help Processing to evaluate if the boolean expression is true or false. For example, you could ask the program to execute a certain block of code only if x > 5. In code, this could look like this:

EXAMPLE:
if (x > 5) {
ellipse(100, 100, 30, 30);
}

Therefore, the circle is only drawn if x > 5 is evaluated true, otherwise Processing will skip this code until eventually, this boolean expression becomes true. This is how one could use relational operators to create conditional statements.

A conditional statement like this can be extended by the functions „else if“ and „else“. This way, you can define what should happen, if the boolean expression is evaluated false. Implemented, it looks like this:


EXAMPLE:
if (x > 5) {
ellipse (100, 100, 30, 30);
} else if (x > 3) {
rect (100, 100, 200, 50);
} else {
background(0);
}

Conditional statements can be combined, too. This is where logical operators come into place. With the aid of „and“, „or“ and „not“ you can define, if the code should be executed if both statements are true or one of them is true. „And“ can be translated into code by &&, „or“ into || and „not“ into !. Using „not“ will inverse the statement. This then looks like this:

EXAMPLE:
if (x > 5 && y < 2) {

}

if (x > 5 || x < 0) {

}

if! (x > 5 && y < 2) {

}

In order to simplify the usage of these conditional statements, boolean variables are created. One can define a boolean variable like any other variable, the only difference is that boolean variables can only be true or false rather than holding a specific value. It can then be inserted into a conditional statement. If the variable is defined to be true, the code is executed and vice versa.

EXAMPLE:
boolean x = true;
if (x) {

}

In this case, the code will be executed since the variable x is defined to be true. However, one can change this definition of x in the course of the code.

EXAMPLE:
x = !x ;
This is how x is changed from true to false and from false to true.