IF
Statement/Command
If is always used with THEN to prompt a decision that affects subsequent action. To do this, the computer tests something to find out whether or not it is true. If it is true, then one course of action follows. If it is untrue, another occurs.
How to use IF and THEN
IF normally forms a statement with THEN. IF is first followed by a numeric value or by a condition, and second by THEN and one or more BASIC statements, for example
80 IF x THEN GO TO 250
240 IF a$="NO" THEN PRINT "THE END": STOP
A constant, variable or expression (such as x above) is considered to be true if it has a non-zero value. In this case the statement following THEN and any more statements in the same line are executed. The program then proceeds to the next line. If the value is 0, then the constant, variable or expression is considered to be false. The following statements are then not executed and the program skips to the next line. In the example, the program will not GO TO line 250 if x is 0.
If a condition (a$="NO") following IF is true then the statements following THEN are executed. If the condition is false, then the program moves to the next line. In this example, if a$ has the value "NO" then "THE END" is displayed and the program stops. If a$ has any other value, the program continues from the next line.
The BASIC gives a true condition a value of 1 and a false condition a value of 0. It recognises any non-zero value as true and 0 as false. A variable can be assigned the value of a condition by a statement such as
70 LET x=a$="NO"
Note that, unlike in some other BASICs, THEN cannot be ommitted before GO TO.
Format
- IF num-expr THEN statement [:statement]
- IF cond THEN statement [:statement]
See also