Comp 101 Else-If Logic

Else-If

When using if-statements, sometimes it can be much easier to specify an if-conditional as a part of an else statement.

Wouldn't you much rather use this...

if (havingFun) {
      print("Yay!!");
} else if (needsHelp) {
      print("Go to office hours!");
} else {
      print("Keep working hard!");
}

...than this?

if (havingFun) {
      print("Yay!!");
}
if (needsHelp) {
      print("Go to office hours!");
} 
if (!havingFun && !needsHelp) {
      print("Keep working hard!");
}

Using else-if statements help us direct the logical flow of a program by increasing our control over which boolean combinations lead to which output. We can make more complex code that does more with fewer lines!

To create an else-if simply add the keyword else following the closing curly brace of the previous if statement and before the following if of your next if statement.

Independent "Ifs" vs. Dependent "Else-Ifs"