If .. Else
- If Statement
- if...else Statement
- if...else if Statement
- Nested if
if (test_condition) {
statement(s);
}
Decision making is required when we want to execute a code only if a certain condition is satisfied. Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True. If the test expression is False, the statement(s) is not executed.
Example
void main() {
int x = 5;
if (x % 2 == 1) {
print("odd");
}
}
if (test_condition) {
body of if
}else{
body of else
}
The if..else statement evaluates test expression and will execute the body of if only when the test condition is True. If the condition is False, the body of else is executed.
Example
void main() {
int y = 6;
if (y % 2 == 1) {
print("odd");
} else {
print("even");
}
}
if ( test_condition_1 ) {
body of if
}
else if( test_condition_2 ){
body of else if
}
else{
body of else
}
The else if allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next else if block and so on.
If all the conditions are False, the body of else is executed.
Only one block among the several if...else if...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple else if blocks.
Example
void main() {
var num = -3.4;
if (num > 0) {
print("Positive number");
} else if (num == 0) {
print("Zero");
} else {
print("Negative number");
}
}
if ( test_condition_1 ){
...
if ( test_condition_2 ){
body of nested if
}
...
}
...
A nested if is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement.
Example
void main() {
var num = 7;
if (num > 0) {
print("Positive number and");
if (num % 2 == 0)
print("even");
else
print("odd");
} else if (num == 0) {
print("Zero");
} else {
print("Negative number");
}
}
odd
Note:
If there is only one statement is present in the “if” or “else” body then you do not need to use the braces. For example :
void main() {
int age = 17;
if (age >= 18)
print("You are eligible for voting");
else
print("You are not eligible for voting");
}
Important Points:
1. else and else..if are optional statements, a program having only “if” statement would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in a if else..if block.
4. If none of the conditions are met then the statements in else block gets executed.