< Previous | Contents | Next >
Using a Sequence of if Statements with else Clauses
You can chain if statements with else clauses together to create a sequence of expressions that get tested in order. The statement associated with the first expression to test true is executed; otherwise, the statement associated with the final (and optional) else clause is run. Here’s the form such a series would take:
if (expression1)
statement1;
else if (expression2)
statement2;
.. .
else if (expressionN)
statementN;
else
statementN+1;
If expression1 is true, statement1 is executed and the rest of the code in the sequence is skipped. Otherwise, expression2 is tested and if true, statement2 is executed and the rest of the code in the sequence is skipped. The computer continues to check each expression in order (through expressionN) and will execute the statement associated with the first expression that is true. If no expression is true, then the statement associated with the final else clause, statementN+1, is executed.
Using a Sequence of if Statements with else Clauses 49