|
The IF and THEN commands are used to compare an expression and then perform some task based on that expression.
IF x = 5 THEN PRINT "x equals 5"
Expression signs You can also enter the following statements, instead of the equals sign:
x > 5 (x is greater than 5) Run the following:
IF (x > 5) THEN PRINT "x is greater than 5"
You can also combine the signs like this:
x >= 5 (x is greater than or equal to 5) x <> 5 (x does not equal 5) Run the following example:
x = 5 IF (x >= 5) THEN PRINT "x is greater than or equal to 5" IF (x <= 5) THEN PRINT "x is less than or equal to 5" IF (x <> 5) THEN PRINT "x does not equal 5"
x is less than or equal to 5 ELSE Using the ELSE command, you can have the program perform a different action if the statement is false.
IF x = 5 THEN PRINT "Yes" ELSE PRINT "No"
END IF END IF allows you to have multiple commands after the IF...THEN statement, but they must start on the line after the IF statement. END IF should appear right after the list of commands.
IF (x = 5) THEN
PRINT a$ END IF The following program uses ELSE with the END IF command:
IF (x = 5) THEN
PRINT a$ ELSE
END IF
ELSEIF The ELSEIF command allows you to perform a secondary action if the first expression was false. Unlike ELSE, this task is only performed if a specified statement is true.
IF (x = 5) THEN
ELSEIF (x = 6) THEN
END IF
You can have multiple ELSEIF commands, along with ELSE.
IF (x = 5) THEN
ELSEIF (x = 6) THEN
ELSEIF (x = 7) THEN
ELSE
END IF
Multiple expressions You can have more than one expression in IF...THEN by using either the OR operator or the AND operator. The OR operator only requires one expression to be true in order to print "Yes" in the following program:
IF (x = 5 OR x = 20) THEN PRINT "Yes"
The AND operator requires both expressions to be true.
IF (x > 5 AND x < 10) THEN PRINT "True"
This is a slightly more complex example:
y = 3 IF ((x > 5 AND x < 10) OR y = 3) THEN PRINT "Correct"
Strings in IF...THEN So far in this chapter, we've only been dealing with numbers, but you can also use strings with the IF...THEN command.
IF (x$ = "Hello" OR x$ = "World") THEN PRINT x$
You can also compare two variable strings:
y$ = "World" IF (x$ <> y$) THEN PRINT x$; " "; y$
Feel free to distribute this tutorial, upload it to your website, link to it from your site, etc. http://www.geocities.com/progsharehouse/qbtutor Mirror: http://development.freeservers.com/qbtutor |