in BASIC ROM:
|List of all BASIC keywords|
Typ: Command General Programming-Syntax: IF <equation> THEN <linenumber> or IF <equation> GOTO <linenumber> or IF <equation> THEN <command>
The BASIC command IF is used to test a "condition". If the condition produces a non-zero value, the statements after the THEN or GOTO are performed. When the condition is false then the BASIC interpreter will ignore the rest of the BASIC commands in the line.
For the condition the following relational operators are useful:
- = equal
- <> unequal
- < less than
- > greater
- <= less-equal
- >= greater-equal
When the command is GOTO, GOSUB or THEN <line>, the system will perform a branch. The performance of branches gets progressively worse as the program size grows. This can be addressed to some degree by understanding the line-lookup process.
Examples[edit | edit source]
10 PRINT CHR$(147); 20 INPUT "2 numbers, please: ";A$, B$ 30 IF A$="" OR B$="" THEN 20 40 A=VAL(A$): B=VAL(B$) 50 IF A>0 THEN PRINT "A is positive and "; 51 IF A<0 THEN PRINT "A is negative and "; 52 IF A=B THEN PRINT "A is equal to B "; 53 IF A<>B THEN PRINT "A is not equal to B "; 54 IF NOT A AND NOT B THEN PRINT ", neither number is -1"; 55 IF A=64 AND B=64 THEN PRINT " !!! BINGO !!!": GOTO 58 56 IF A=B AND A=0 GOTO 58 57 IF (A AND B=0) OR (NOT B AND A=0) THEN END 58 FOR X=0 TO 3000: NEXT 59 GOTO 10
Technically what happens is the expression is evaluated, and if the expression is 0, the statements after THEN or GOTO are not executed. If the expression is non-zero, the statements after THEN or GOTO will be executed. So something like this can be used:
10 IF A THEN PRINT "A is nonzero"
Note that Microsoft-derived BASICs like Commodore BASIC treat all of the statements on the line after then THEN as part of the IF statement, and they will all run or not as a group. This is not true of all BASICs, for instance, the original Dartmouth BASIC treated only the statement immediately after the THEN as part of the IF. To understand the difference, consider this code:
10 IF 1=0 THEN PRINT"HELLO":PRINT"WORLD"
In Dartmouth BASIC and others that follow the same pattern, the output of this line is WORLD. In Commodore BASIC, there will be no output because both PRINT statements are considered part of the IF.
An example of how to compute the maximum among three numbers:
10 input "enter a";a 20 input "enter b";b 30 input "enter c";c 40 if a>=b and a>=c then m=a:goto 70 50 if b>=c then m=b:goto 70 60 m=c 70 print "max:";m
An example of how to solve a quadratic equation ax2 + bx + c=0:
10 print "enter equation" 20 input "a";a 30 input "b";b 40 input "c";c 50 d=b^2-4*a*c 60 if d<0 then print "no real roots":goto 200 70 if d=0 then print "one root:";-b/(2*a):goto 200 80 print "two roots" 90 x1=(-b+sqr(d))/(2*a) 100 x2=(-b-sqr(d))/(2*a) 110 print "x1:";x1 120 print "x2:";x2 200 end