Lesson 6: Conditional, Equality and Relational Operators

The “if” statement

The “if” statement allows us to execute a statement or a block of code, if a certain condition is TRUE.

Syntax:

Single Statement

if ( condition ) statement;
if ( x > 10 ) Serial.println(x);

Block of code between { }

if ( condition ) {
statement;
statement;
statement;
}
if ( x > 10 ) {
Serial.print(“x = “);
Serial.println(x);
}

The “if-else” statements

The “if-else” statement allows us to execute a statement or block of code if a condition is TRUE, but if the condition is FALSE, it allows us to execute a different statement of block of code.

Allows us to select between two or more alternatives.

Syntax:

Single Statement
if ( condition )
statement;
else
statement;
if ( x > 10 )
Serial.print(“x is > 10”);
else
Serial.print(“x is not > 10”);

Block of code between { }

if ( condition ) {
statement;
statement;
statement;
}
if ( x > 10 ) {
Serial.print(“x = “);
Serial.println(x);
} else {
Serial.print(“x is not > 10. ”);
Serial.println(“x = “ + x);
}

The “if-else-if” statements

Syntax:

if ( condition )
statement;
else if ( condition )
statement;
else
statement;
if ( x > 10 )
Serial.println(“x is > 10”);
else if ( x > 20 )
Serial.println(“x is > 20”);
else
Serial.println(“x is not > 10 or 20”)
if ( condition ) {
statement;
statement;
} else if {
statement;
statement;
} else {
statement;
statement;
}
if ( x > 10 ) {
Serial.print(“x = “);
Serial.println(x);
} else if ( x > 20) {
Serial.print(“x is not > 10. ”);
Serial.print(“x = “);
Serial.println(x);
} else {
Serial.print(“x = “;
Serial.println(x);
}

Equality and Relational Operators

The equality and relational operators determine if one operand is equal to, greater than, less than or not equal to another operand.

==

Equal to

Keep in mind that you use “==” to test equality not “=”

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Conditional Operators

&&

AND

The “&” symbol is called ampersand

e.g.

if (digitalRead(2) == LOW && digitalRead(3) == LOW) {
// …
}

||

OR

The “|” symbol is called the pipe symbol. It is the symbol located above the Enter key on a US QWERTY keyboard.

e.g.

if (x > 0 || y > 0) {
// …
}

!

NOT

TRUE if the operand is false

e.g.

if (!x) {
// …
}