Arduino if-else and else-if

if-else and else-if Statements

  • The else and else-if both are used after writing the if statement. 
  • It allows multiple conditions to be execute all together.
  • The if-else condition is made up of two statements: if () and else ()
  • If the output of the If () statement is false, the condition in the else statement is implemented.
The flowchart is as follows:

if-else statement

Let us take example

if (condition)  
{  
// statements  
}  
else  
{  
//statements  
}  

Example 1:

int a = 5;  
int b= 6;  
void setup ( )  
{  
Serial.begin ( 9600 );  
}  
void loop ( )  
{   
if ( a > b )  
{  
Serial.println ( " a is greater " );  
}  
else  
{  
Serial.println ( " a is smaller " );  
}  

Expected Output:
  • In above example, the values are initialized in variables a and b. The message satisfying the condition will be printed. 

Example 2:

const int LED1 = 4;  
int x = 150 ;  
void setup ( )  
{   
Serial.begin( 9600 );  
pinMode ( LED1, OUTPUT);  
}  
void loop ( )  
{   
if ( x > 100 )  
{  
digitalWrite(LED1, HIGH);  
Serial.println ( " LED1 will light +++");  
delay (500);  
}  
else  
{  
Serial.println ( "LED1 will not light");   
}  
}  

Expected Output: 
LED1 will light +++
  • If the initialized value of x is less than 100, the message ' LED1 will not light ' will be printed in the output.
Else if
  • The else if statement can be used with or without the else ( ) statement. 
  • We can include multiple else if statements in a program.
if (condition)  
{  
// statements  
}  
else if ( condition)  
{  
// statements  
// only if the first condition is false and the second is true  
}  
else  
{  
//statements  
 

Example 1:

int i = 2;  
int j = 3;  
void setup ( )  
{  
  Serial.begin(9600);  
}  
void loop ( )  
{  
  if ( i > j )  
  {  
    Serial.println( " I is greater ");  
  }  
  else if ( i < j )  
  {  
    Serial.println( " J is greater " );  
  }  
  else  
  {  
    Serial.println( " Both are equal " );  
  }  
}  

Expected Output: 
J is greater

Post a Comment

Previous Post Next Post