Thursday, 28 January 2010

SELECT CASE

SELECT CASE Statements are a simple way to make a selection based on some kind of program value or user input. The SELECT CASE statements, also known as a Switch statement in Pascal C++ and Java  are more succinct than IF THEN ELSE Statements and possibly  more efficient code for compilation. Also in this program I will introduce another new command UPCASE$ So to demonstrate this create a new program and type the following code in and run.

DIM KeyPress AS STRING * 1

CLS 'Clear The Screen

DO WHILE KeyPress$ = ""
    KeyPress$ = INKEY$   ,Test For a KeyPress
    KeyPress$ =  UCASE$ (KeyPress$) ,Chance Input to Uppercase
LOOP

SELECT CASE KeyPress$

  CASE "A" TO "G"
   PRINT "You Pressed A To G"

  CASE "H" TO "P"
   PRINT "You Pressed Q" TO "Z"

END SELECT

As you will have noticed the UCASE$ function returns an uppercase letter which saves checking  and  the SELECT CASE  tests can be used for single values and values between parameters. It's a better construction for long lists than IF THEN statements but lacks some of the flexibility.

As an extra exercise open the the 'Celsius to Fahrenheit Fahrenheit  to Celsius' program and change the selection SUBroutine to use a SELECT CASE statement instead of an IF THEN. To make it more interesting you could add another  conversions such as LB to KG  of Yards to Meters.  Of course remember to change the instructions and add another choice for the user to select.

No comments:

Post a Comment