Dart If-else-if statement
If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular block of statements is executed.
Syntax:
if ( condition 1 ) { Statements ; } else if ( condition 2 ) { Statements ; } else { Statement ; }
This is also known as the else…if ladder. The statements are executed sequentially and if none of the condition evaluates to true then the else block is executed by default.
Program
Consider the following code in Dart that explains the concept of if-else-if,
import 'dart:io'; void main( ) { // accepting the value of marks from the user print( ' Enter the marks : ' ) ; int? marks = int.parse( stdin.readLineSync( ) ! ) ; // checking the marks with the user entered marks, whichever condition evaluates to true, the print statement corresponding to that gets printed if ( marks > 85 ) { print( " A + " ) ; } else if ( marks > 75 ) { print( " A " ) ; } else if ( marks > 65 ) { print( " B + " ) ; } else if ( marks > 55 ) { print( " B " ) ; } else if ( marks > 45 ) { print( " C + " ) ; } else if ( marks > 35 ) { print( " C " ) ; } else { print( " Fail ! " ) ; } }
Output :
Enter the marks : 65 B Enter the marks : 35 Fail!
Nested if – else statement
Nest if – else statement refers to one if – else inside the another if – else.
Program
Consider the following code in Dart that explains nested if – else statement,
import 'dart:io'; void main( ) { // accepting the value of a from the user print( ' Enter the value of a : ' ) ; int? a = int.parse( stdin.readLineSync( ) ! ) ; // accepting the value of b from the user print( ' Enter the value of b : ' ) ; int? b = int.parse( stdin.readLineSync( ) ! ) ; // accepting the value of c from the user print(' Enter the value of c : ' ) ; int? c = int.parse( stdin.readLineSync( ) ! ) ; // checking if a is greater than b if ( a > b ) { // if true, then check if a is greater than c if ( a > c ) { print( " A is the greatest of all ! " ) ; } else { print( " C is the greatest of all ! ") ; } // if a is not greater than b, then check if b is greater than c } else if ( b > c ) { print( " B is the greatest of all ! " ) ; } else { print( " C is the greatest of all ! " ) ; } }
Output:
Enter the value of a : 25 Enter the value of b : 45 Enter the value of c : 23 B is the greatest of all !