Wednesday, March 11, 2015

Conditional Statements

Previous Topic    Course Outline    Next Topic

Time to write a simple if-else statement.

1
2
3
4
5
if (<condition>) {
    //statements to be executed when condition is true
} else {
    //statements to be executed when condition is false
}

The else block is optional. If no action is required when the condition is false, omit the else block.


Nested-If example:

1
2
3
4
5
6
7
8
if (<condition>) {
    //statement when condition is true
} else {
    //some statements here
    if (<another condition>) {
       //statements to be executed when <another condition> is false
    }
}

Use nested-if when you need to perform some statements outside the inner if-block but if you don't need to put something in //some statements here, you can use the else-if block.

 1
 2
 3
 4
 5
 6
 7
 8
 9
if (<condition1>) {
    //statement1
} else if (<condition2>) {
    //statement2
} else if (<condition3>) {
    //statement3 when condition is true
} else {
    //statements to be executed when all condition fails
}

Only the block under the first condition that equates to true will be executed. So yeah, I'm basically saying that the order is important. It's a good practice to arrange the conditions from the most to the least probable. Even in real life, we first verify the obvious before resorting to a new hypothesis.


Previous Topic    Course Outline    Next Topic

No comments:

Post a Comment