Logic in BASIC

See all articles from QZX v4 n7
Author(s): Ambrose Barry (W4GHV)
Publication: QZX
Pub Details: QZX v4 n7 (Volume 4, Issue 7)
Date: June 1986
Pages: 8-9

This article is adapted from one which appeared in the Computer Astronomy Network newsletter as reprinted in the Hampton Roads T/S User Group Newsletter.

You can speed up your BASIC programs and increase available storage if you code with logical expressions in some unusual places. These logical expressions are often overlooked program statements that can accomplish the above and also clean up many GOTO statements that often tend to clutter up a program listing.

A logical statement has two conditions, true or false, which are represented by the values ‘1’ and ‘0’ respectively in our Sinclair computers.

An example of a logical assignment statement might be

500 Let A = (X >= 10) + 15

If the value of ‘X’ is equal to or greater than 10, then ‘A’ will have the value ‘1’. For ‘X’ less than 10, the value of ‘A’ will be ‘0’.

A logical expression in brackets may be added to and/or multiplied by other values. for example, with the statement

500 LET A = 100 * (X >= 10) + 15

‘A’ takes on the value 115 when the logical expression is true and 15 when it is false.

To illustrate some of the applications of this, the following code was borrowed from “Timex/Sinclair 1000 Astronomy”, in which day-month calculations are made:

350 IF M = 2 THEN LET D = 31
360 IF M = 3 THEN LET D = 59
:
:
450 IF M = 12 THEN LET D = 334

Here, eleven statements must be individually interpreted and evaluated by the computer. The more statements, the longer the program takes to arrive at the results. If the code is repetitively looped, the time involved is further magnified. Hence, if several statements can be combined, fewer interpretations are required decreasing program execution time. To illustrate, the following single statement can replace the above code and will execute in about 30 percent of the time:

350 LET D = 31 * (M = 2) + 59 * (M = 3) +...+ 334 * (M = 12)

At this point in the program, M has an integer value between 2 and 12. Because it can only have one of these values, only one logical statement (inside the parentheses) will be true. The appropriate value will then be assigned to ‘D’ because it is the only number multiplied by ‘1’.

Computed GOTO statements can also be replaced in a similar manner. Instead of this:

100 IF A < 10 THEN GOTO 400
110 IF A = 10 THEN GOTO 500
120 IF A > 10 THEN GOTO 600

the following could be substituted:

100 GOTO 400 * (A<10) + 500 * (A=10) + 600 * (A>10)

As was implied in the opening statement, this method of coding, as well as being more efficient in execution, also occupies less RAM allowing you to write longer, more complex programs in much less space.