Arduino IDE: the conditional construction IF #4

Arduino IDE

Welcome back to our programming tutorial using the Arduino IDE. Today we will cover the conditional if construct.

You can take a look at the previous chapters of the course here:

The instructions for the problem solving procedure (algorithm) are organized according to schemes that can be classified into three fundamental constructs. Today we will analyze the the control structures.

The instructions are executed one after the other following the same order they were written.

The if structure is basically a binary alternative selection that allows you to choose between two possible program paths.You use the if statement whenever you need to execute an instruction following the occurrence of a certain condition.

The syntax is as follows:

If the condition is true, instruction1 is executed, otherwise (if the condition is false) instruction2 is executed.

Instruction1 and instruction2 can indicate, as happens in most cases, not just a single instruction but a group (block) of instructions.

The condition is a Boolean expression whose truth is assessed, the comparison and logical operators are then used (read Arduino IDE: arithmetic and logical operators #3 if the previous sentence does not make sense for you).

The ELSE attribute is an optional attribute of the IF statement. The ELSE attribute defines either one instruction, or  or a block of instructions delimited by two braces.

Conditional if statements can be nested to create more refined control structures. Here is an example:

test condition for if

Each nested if block can be accompanied by the corresponding else if and else blocks. The Arduino IDE programming language standard recommends a theoretical limit of 256 nesting levels for flow control structures, which goes well beyond the limit imposed by common sense.

Here is a sample program template using a complete if structure taken from the Arduino page:

In our next article we will explain you how to turn on a LED with a button, using the conditional if structure.

Previous articles:

Follow us to keep yourself updated with the news!

Simone Candido è un ragazzo appassionato del mondo tech nella sua totalità. Simone ama immedesimarsi in nuove esperienze, la sua filosofia si basa sulla irrefrenabile voglia di ampliare a 360° le sue conoscenze abbracciando tutti i campi del sapere, in quanto ritiene che il sapere umano sia il connubio perfetto tra cultura umanistica e scientifica.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.