It is very common in programming to have more than two ways (or branches). e.g., printing the grade of a student like "Distinction", "First Class", "Second Class" and "Fail" instead of simply "Pass" or "Fail". In this case if-else-if ladder will be very useful.
if( condition1 ) { statement1; // BLOCK 1 } else if( condition2 ) { statement2; // BLOCK 2 } else if( condition3 ) { statement3; // BLOCK 3 } else { statement4; // BLOCK 4 } if conditions are executed top down. If the condition1 is true , only statement1 is executed, the other statements - statement2 and statement3 will not be executed. If the condition1 is false and condition2 is true , then only statement2 is executed. If condition1, condition2 are false but condition3 is true , then only statement3 is executed. If all the conditions - condition1, condition2 and condition3 are false , then statement4 is executed. Also note that when condition1 is true , irrespective of whether other conditions are true or false , only statement1 will be executed. statement2 and statement3 will not be executed.
Print Student Grade CODE class PrintStudentGrade OUTPUT First Class DESCRIPTION Since the THINGS TO TRY
2-min video about if-else-if ladder
|