The if else if Ladder
A common programming construct that is based upon a sequence Us is the if-else-if ladder.It looks like this.
1he if statements are executed from the top down. As soon as one of the conditions
controlling is true, ‘the statement associated with that if is executed, and the rest
of the ladder is by passeo.. T none of the conditions is true, then the final else statement
will be executed. The
e final else Ia default condition; that is, if all other
,conditional ts.fail,then the last ‘else tenement is performed. If there is no final else and all other conditions are false, then no action will take’place, Here is a program that Uses an if-else-if ladder to determine which season a particular month is in.
// Demonstrate if-else-if statements.
class If Else .(
public static void main(String args[l) ) (
int month =4; =II April
if (month = 12 I I month == 1 I I month == 2)
season = ‘Winter”
else’ if (month == 3 II month == 4 I 1,_month== 5)
season= “Spring”is i
else if (month’ = ‘6 f I month = 7 I I month == 8)
season ‘” Summer’ i
else if (month == 9 I I month = =7 l l month = = 8
season = Autumn”;
season= Bougs Month=i
System”out.print ln(“April is in the” + .season + “.”);
Here is the output produced by the program:
April is in the Spring
You might want to experiment with this program before moving on. As you will . find, no matter what value you give month, one and only one assignment statement
within the ladder will be’ executed.