Tiny BASIC

Interpreter and Compiler Project

Storing Calculation Results

So far we've used variables to store numbers entered directly by the user. Calculations have been performed at the time when we want to display the results. Somtimes, though, we want to perform a calculation and store the result in a variable. For this, we have the LET instruction. The following program asks for a number, and then prints out its multiplication table.

10 PRINT "Which multiplication table?"
20 INPUT M
30 LET C=2
40 PRINT C,"*",M,"=",C*M
50 LET C=C+1
60 IF C<=12 THEN GOTO 40

The LET command is used twice in this program, to control a counter (called C) that counts through the rows of the table. Since everyone knows that 1*n=n, we can skip that row, and line 30 starts the counter at 2. After printing the row, line 50 calculates C+1, and stores the result back into C, overwriting what was there before. We don't bother using LET to store C*M in this example, because once we've calculated and printed it, we don't need it any more. If our program were to do something more with C*M, we might store it with the line:

45 LET P=C*M

which would store the product in P, after which we could refer to P instead of performing the multiplication again. As with all other commands, we can use LET in conjunction with IF to do things conditionally. The following program works out the cost of a train ticket based on the passenger's age:

10 PRINT "Age?"
20 INPUT A
30 IF A<16 THEN LET F=5
40 IF A>=16 THEN LET F=10
50 PRINT "Fare: ",F

This program would charge a child 5 or an adult 10, assuming those aged 16 and above are considered adults for the purpose.

Next: Skipping Ahead

Comments

New Comment

Yes No