if, else-if, else
Using else-if allows us to test a new condition if the previous condition is false
:
if (condition1) {
// executed if condition1 is true
} else if(condition2) {
// executed if condition1 is false and condition2 is true
} else {
// executed if condition1 is false and condition2 is false
}
The following flowchart example describes the else-if control statement:
- We start with the variable
age
with a value of25
. - Then we have a condition to check if the
age
is less than or equal to5
:- If
age <= 5
resolvestrue
(yes), then we will printInfant 0-5 years old
. - If
age <= 5
resolvesfalse
(no), we will check the next condition.
- If
- The next condition checks if the
age
is less than18
:- If
age < 18
resolvestrue
(yes), then we will printTeenager 6-17 years old
. - If
age < 18
resolvesfalse
(no), we will check the last condition.
- If
- The last condition checks if the
age
is less than50
:- If
age < 50
resolvestrue
(yes), then we will printAdult 18-49 years old
. - If
age < 18
resolvesfalse
(no), then we will printElderly 50 or more years old
.
- If
- The program continues...
Let's run the code of DartPad:
After running in DartPad, Adult 18-49 years old
is printed in the console because the third condition
was true
. You can try changing the value of age
to a value lower than 18
. What is the result?