Search

Friday, December 14, 2018

The if -else-if Ladder

A common programming construct that is based upon the nested if is the if-else-if ladder. It looks like this:
if(condition)
 statement;
else
if(condition)
statement;
else if
(condition) statement;
else statement;
 The conditional expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder is bypassed. If none of the conditions is true, the final else statement will be executed. The final else often acts as a default condition; that is, if all other conditional tests fail, the last else statement is performed. If there is no final else and all other conditions are false, no action will take place. The following program demonstrates the if-else-if ladder:

// Demonstrate an if-else-if ladder.
class Ladder
{ public static void main(String args[])
{
 int x;
for(x=0;x<6; x++)
{
 if(x==1)
System.out.println("x is one");
else if(x==2)
System.out.println("x is two");
 else if(x==3)
 System.out.println("x is three");
else if(x==4)
System.out.println("x is four");
else System.out.println("x is not between 1 and 4");
 }
}
}
The program produces the following output:
x is not between 1 and 4 x is one x is two x is three x is four x is not between 1 and 4
As you can see, the default else is executed only if none of the preceding if statements succeeds.



0 comments:

Post a Comment