3.4 else if Statements
Building on the previous two sections, you are going to look at adding the else if
clause to our if blocks. The else if clause allows for a multi-way selection by using different conditional statements to represent different conditions.
You can add the else if
keyword between your if and your else statement. If boolean expression one evaluates to false
, then boolean expression two gets evaluated next. If boolean expression two also turns out to be false
, the code within the else
segment will run.
In the example above, notice how only one condition is executed. With x
at 19, it executes the first block of code. Even though x
is also less than 30, that block of code is skipped since only one block is executed. After the if clause is executed all other clauses are skipped.
It is important to note that you can have as many else if statements as you want, or you can have none. When looking at conditional blocks of code, the only required statement is the if
statement. This can optionally be followed with any number of else if
statements, and then optionally one else
statement.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
What is the output of the following code snippet?
Every year, salmon return from the saltwater they usually live in a freshwater river to spawn (lay eggs). Some people like to go and watch the salmon swim upstream to their favorite spawning places, especially at fish farms.
There are several different varieties of salmon. Some spawn in the spring and most spawn in the fall.
Your task is to write a program that takes the month of the year as an integer and output if it is “Spring spawning season”, “Fall spawning season”, or “Not spawning season”.
The spring spawning season lasts from April to June (months 4- 6). The fall spawning season lasts from October to December (months 10 - 12).
Remember that in an if
-else if
statement, the first statement that evaluates to true
is the one whose body is executed. Therefore, you will need to check the months in numerical order.