if else

Description

The if...else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped. An else clause (if at all exists) will be executed if the condition in the if statement results in false. The 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 are allowed.

Syntax

if (condition1) { // do Thing A } else if (condition2) { // do Thing B } else { // do Thing C }

If there is only one statement inside if or else, the curly braces can be omitted.

if (condition1) // a singe statement; else if (condition2) { // multiple statements; } else if (condition2) // a singe statement; else // a singe statement;

Example Code

Example Code 1

The below code deternine numbers are odd or even

int i = 0; void setup() { Serial.begin(9600); } void loop() { if ((i % 2) == 0) { Serial.print("Inside the IF statement: i = "); Serial.print(i); Serial.println(", even number"); } else { Serial.print("Inside the IF statement: i = "); Serial.print(i); Serial.println(", odd number"); } i++; // increase i by 1 delay(500); }

The result on Serial Monitor:

COM6
Send
Inside the IF statement: i = 0, even number Inside the IF statement: i = 1, odd number Inside the IF statement: i = 2, even number Inside the IF statement: i = 3, odd number Inside the IF statement: i = 4, even number Inside the IF statement: i = 5, odd number Inside the IF statement: i = 6, even number Inside the IF statement: i = 7, odd number
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Example Code 2

Below is an extract from a code for temperature sensor system

if (temperature >= 70) { // Danger! Shut down the system. } else if (temperature >= 60) { // 60 <= temperature < 70 // Warning! User attention required. } else { // temperature < 60 // Safe! Continue usual tasks. }

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Please note: These are Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

※ OUR MESSAGES