Dart Programming - If Else Statement



An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if block evaluates to false.

Following is the syntax.

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

If the Boolean expression evaluates to be true, then the if block of code will be executed, otherwise else block of code will be executed.

The following illustration shows the flowchart of the if…else statement.

If-else Statement

The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.

Example - Simple if…else

The following example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same.

void main() { 
   var num = 12; 
   if (num % 2==0) { 
      print("Even"); 
   } else { 
      print("Odd"); 
   } 
}

The following output is displayed on successful execution of the above code.

Even
dart_programming_decision_making.htm
Advertisements