Dart if-else Statement

 

Dart if-else Statement

In Dart, if-block is executed when the given condition is true. If the given condition is false, else-block is executed. The else block is associated with the if-block.

Dart if…else Statement Flow Diagram

Dart if-else Statement

Syntax:

  1. if(condition) {  
  2.       // statement(s);  
  3. else {  
  4.     // statement(s);  
  5. }  

Here, if -else statement is used for either types of result TRUE or False. If the given condition evaluates true, then if body is executed and if the given condition evaluates false; then, the else body is executed.

Let's understand the following example.

Example -

  1. void main() {  
  2.      var x = 20;  
  3.      var y = 30;  
  4.     print("if-else statement example");  
  5.   
  6.     if(x > y){  
  7.          print("x is greater than y");     
  8. else {  
  9.          print("y is greater than x");  
  10.   
  11. };  
  12.   
  13. }  

Output:

if-else statement example
y is greater than x

Explanation -

In the above code, we have two variables which stored integer value. The given condition evaluated false then it printed the else-block.

Example -2 Write a program to find the given number is even or odd.

  1. void main() {  
  2.      var num = 20;  
  3.        
  4.     print("if-else statement example");  
  5.   
  6.     if(num%2 == 0){  
  7.          print("The given number is even");     
  8. else {  
  9.          print("The given number is odd");  
  10. };  
  11. }  

Output:

If-else statement example
The given number is even

Explanation -

In the above example, we have an integer variable num which stored 20 and we used the if-else statement to check whether a given number is even of odd. The given condition evaluated true because modulus of 20 is equal to 0 then it printed the given number is even on the screen

Comments