The else if ladder:



There is another way of putting if’s together when multipath decisions are involved. A multipath decision is a chain of if’s in which the statement associated with each else is an if. General form:

The construct is known as else if ladder. The conditions are evaluated from the top (of the ladder), downwards. As soon as a true condition is found, the statement associated with it executed and the control is transferred to the statement – x (skipping the rest of ladder). When all the n conditions become false, then the final else containing the default will be executed. Figure show the logic of else if ladder.


For Example:
Let us consider an example of grading the students in an academic institution. Grading is done according to following rule:
Average Marks                                                                                  Marks
80 to 100                                                                                             Honors
60 to 79                                                                                              First Divisions
50 to 59                                                                                               Second Divisions
40 to 49                                                                                               Third Divisions
0 to 39                                                                                                 Fail

Sol: This grading is done using else if ladder as follows :
if ( marks >79 )
{
          grade= “honors”;
}
else if ( marks >59 )
{
          grade= “First Division”;
}
else if ( marks > 49 )
{
          grade= “ Second Division”;
}
else if ( marks > 39 )
{
          grade= “Third Division”;
}
else
          grade= “Fail”;


Previous                                                                                    Next


Powered by Blogger.