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.

194<br />

Making Multiple Choices with the SELECT CASE Statement<br />

With a switch statement in a curly bracket language, like C, you can do the<br />

following:<br />

switch (age)<br />

{<br />

case 67:<br />

case 66:<br />

case 65: status = retired;<br />

break;<br />

case 21: status = working;<br />

break;<br />

case 15: status – student;<br />

}<br />

By not using the break command if the value of the age variable is 67 or 66,<br />

the computer just continues down, line by line, until it runs the command if<br />

the age variable was 65. Then it hits the break command directly under the<br />

status = retired command and stops.<br />

The switch command can be easier to read because all the matching values<br />

(67, 66, 65, 21, and 15) appear in a vertical column. The equivalent SELECT<br />

CASE statement can be slightly harder to read because all the values don’t<br />

line up in a single vertical column.<br />

Checking a range of values<br />

The problem with the SELECT CASE statement is that it needs to match a<br />

value exactly. Although you could type in all possible values to match, that<br />

can get clumsy, as in the following that sets Status = retired if the Age<br />

variable is between 65 and 75:<br />

SELECT CASE Age<br />

CASE 65, 67, 68, 69, 70, 71, 72, 73, 74, 75<br />

Status = Retired<br />

CASE 21<br />

Status – Working<br />

CASE 15<br />

Status = Student<br />

END SELECT<br />

To avoid this problem, many languages let you check <strong>for</strong> a range of values.<br />

So if you want to check if a variable is equal or greater than 65 and less than<br />

or equal to 75, you could define the range of 65 TO 75 like this:<br />

SELECT CASE Age<br />

CASE 65 TO 75<br />

Status = Retired<br />

CASE 21<br />

Status – Working

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

Saved successfully!

Ooh no, something went wrong!