Else statements is the statement used the conditions of the if turns out to be false and then the else statement is executed. When we know that the statement turn out to be true then we use if statement only but if we want for the false evaluation to write an statement then else is also used along with if. Syntax
void main(){
if(boolean_expression){
//statements
}else{
//statements
}
}
Example
void main(){
if(6%2 == 0){
print("6 is an even number");
}else{
print("6 is an odd number.");
}
}
Output
6 is an even number
The else and else if ladder are useful when there are multiple conditions to choose from for the true output. Syntax
if(boolean_expression1{
//statememts if expression1 evaluates true
}else if(boolean_expression2){
//statements if expression2 evaluates true
}else{
//statements if both expressions are false
})
Example
void main() {
var num = 2;
if(num > 0) {
print("${num} is positive");
}
else if(num < 0) {
print("${num} is negative");
} else {
print("${num} is neither positive nor negative");
}
}
Output
2 is positive