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

Syntax:

if(condition) {  
      // statement(s);  
} else {  
    // statement(s);  
}  

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 –

void main() {  
     var x = 20;  
     var y = 30;  
    print("if-else statement example");  
  
    if(x > y){  
         print("x is greater than y");     
} else {  
         print("y is greater than x");  
  
};  
  
}  

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.

void main() {  
     var num = 20;  
       
    print("if-else statement example");  
  
    if(num%2 == 0){  
         print("The given number is even");     
} else {  
         print("The given number is odd");  
};  
}  

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.

Leave a comment

Your email address will not be published. Required fields are marked *