15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Picking Three or More Choices with the IF-THEN-ELSEIF Statement 185<br />

command #2<br />

.<br />

.<br />

command #3<br />

)<br />

The IF-THEN-ELSE statement tells the computer, “Check if something is<br />

True. If so, follow this set of commands. Otherwise, follow this second set of<br />

commands.”<br />

One problem with the IF-THEN-ELSE statement is that it only checks a<br />

single condition. If that single condition is False, it always runs its second<br />

set of commands, such as<br />

IF (Salary > 100000) THEN<br />

TaxRate = 0.45<br />

ELSE<br />

TaxRate = 0.30<br />

END IF<br />

In this BASIC language example, if the value of the Salary variable is greater<br />

than 100000, the TaxRate variable is always set to 0.45.<br />

Book II<br />

Chapter 4<br />

Making Decisions<br />

by Branching<br />

However, if the Salary variable isn’t greater than 100000 (it’s less than or<br />

equal to 100000), the ELSE portion of the IF-THEN-ELSE statement always<br />

sets the TaxRate variable to 0.30.<br />

The IF-THEN-ELSE always gives the computer a choice of exactly two,<br />

mutually exclusive choices. What if you want to give the computer three or<br />

more possible choices? Then you must use the IF-THEN-ELSEIF statement.<br />

Picking Three or More Choices with<br />

the IF-THEN-ELSEIF Statement<br />

The IF-THEN-ELSEIF statement offers two advantages over the IF-THEN-<br />

ELSE statement:<br />

✦ You can check a condition <strong>for</strong> each set of commands.<br />

✦ You can define three or more separate sets of commands <strong>for</strong> the computer<br />

to follow.<br />

Not all <strong>programming</strong> languages, such as C/C++, offer the IF-THEN-ELSEIF<br />

statement.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!