Arduino for beginners – if / else statement

An if statement can be followed by an optional else statement, which executes when the expression is false.

Syntax

The syntax of an if…else statement is

[codesyntax lang=”cpp”]

if(expression) 
{
/* statement(s) will execute if the expression is true */
}
else 
{
/* statement(s) will execute if the expression is false */
}

[/codesyntax]
If the expression evaluates to true, then the if block will be executed, otherwise, the else block will be executed.

else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.

Each test will proceed to the next one until a true test is encountered. When a true test is found, its associated block of code is run, and the program then skips to the line following the entire if/else construction. If no test proves to be true, the default else block is executed, if one is present, and sets the default behavior.

Note that an else if block may be used with or without a terminating else block and vice versa. An unlimited number of such else if branches is allowed.

Lets look at some examples

Code

 

[codesyntax lang=”cpp”]

void setup() 
{
int i = 1;

Serial.begin(9600);
while(i<=10)
{
if(i >=5 )
{
Serial.print("if (true) = ");
Serial.println(i);
}
else
{
Serial.print("else (false) = ");
Serial.println(i);
}
i++;
}
}

void loop() 
{
}

[/codesyntax]

 
Open the serial monitor and you will see the following

else (false) = 1
else (false) = 2
else (false) = 3
else (false) = 4
if (true) = 5
if (true) = 6
if (true) = 7
if (true) = 8
if (true) = 9
if (true) = 10
Lets look at en if / else if / else example

 

[codesyntax lang=”cpp”]

void setup() 
{
int i = 1;

Serial.begin(9600);
while(i<=30)
{
if(i >=1 && i <=10 ) //runs from 5 to 10
{
Serial.print("if = ");
Serial.println(i);
}
else if (i >=11 && i<=20) //runs from 11 to 20
{
Serial.print("elseif = ");
Serial.println(i);
}
else
{
Serial.print("else = "); // runs from 1 to 4
Serial.println(i);
}
i++;
}
}

void loop() {
}

[/codesyntax]

 
Open the serial monitor window

if = 1
if = 2
if = 3
if = 4
if = 5
if = 6
if = 7
if = 8
if = 9
if = 10
elseif = 11
elseif = 12
elseif = 13
elseif = 14
elseif = 15
elseif = 16
elseif = 17
elseif = 18
elseif = 19
elseif = 20
else = 21
else = 22
else = 23
else = 24
else = 25
else = 26
else = 27
else = 28
else = 29
else = 30

This div height required for enabling the sticky sidebar
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :