0

what's the difference between 'if else' and 'else if'? and how are they used?

19th Jan 2017, 8:23 AM
Chen Chee Kin
2 Answers
+ 9
Keep it simple. If tests the 1st condition, and if it meets the expression it will enter the code block. Else is the last option that will get executed if it didn't meet the first. Think of if, else if, else if, else if, else as a switch condition: if (this is right){ do this }else if (test this one){ do this if it does }else if (or maybe this){ do this instead }else{ do this as the last resort or think default as none of the above worked } I would use a switch statement if gets too long, it's very similar to the above logic.
19th Jan 2017, 8:38 AM
Mark Foxx
Mark Foxx - avatar
+ 3
if(i == 0) ... //if i =0 this will work and skip following statement else if(i == 1) ...//if i not equal to 0 and if i =1 this will work and skip following statement else if(i == 2) ...// if i not equal to 0 and 1 and if i==2 the statement will execute if(i == 0) ...//if i =0 this will work and check the following conditions also if(i == 1) ...//regardless of i == 0 check, this if condition is checked if(i == 2) ...//regardless of i == 0 and i == 2 check ,this if condition is checked
19th Jan 2017, 8:33 AM
Alex
Alex - avatar