Chapter 3 of 12
Count the supplies
Lay six imaginary food packs on the table. Spend one on each of three turns. How many do you expect after turn one? After turn three? Your prediction is a perfectly good way to test a computer program.
Keep one number in working memory
Open RATIONS.bas and read the listing before you run it. A name without a dollar sign can hold a number. Here S stands for supplies and T stands for the current turn.
10 WIDTH 40:CLS
20 S=6
30 FOR T=1 TO 3
40 S=S-1
60 PRINT "TURN";T;" SUPPLIES";S
70 NEXT T
80 END
Read line 40 aloud as “take the old number of supplies, subtract one, and store the result back under S.” BASIC works out the expression on the right before it replaces the old value on the left. On the first trip through the line the arithmetic is six minus one. On the next trip it is five minus one. The same line can do a different calculation each time.
Take another turn
FOR sets T to 1 and gives the loop a last turn of 3. Line 40 spends one pack; line 60 prints the current turn and what is left. At NEXT T, BASIC adds one to the counter. If another turn fits, BASIC goes back to the first instruction inside the loop. Otherwise it carries on after NEXT.
Choose Run in the editor. Compare your pencil-and-paper answer with the guest screen.
| Turn when line 60 prints | Supplies arriving at line 40 | Supplies printed at line 60 |
|---|---|---|
| 1 | 6 | 5 |
| 2 | 5 | 4 |
| 3 | 4 | 3 |
At OK, type PRINT S,T. The CoCo prints 3 and 4 in separate fields. The 4 is a surprise worth keeping: NEXT moved the counter on one final time and tested it. Four was past the end. There was never a fourth trip through line 60. A comma in PRINT separates fields; the semicolons in the original listing keep the labels and numbers close together.
Check the arithmetic before changing a program
At the prompt, try PRINT 6-1*3. The answer, 3, agrees with the final cargo count. That single calculation tells you the amount left at the end. The loop also tells a crew member how much is left during each turn. Try PRINT (6-1)*3 and the answer becomes 15. The parentheses asked the CoCo to repeat five packs three times.
Choose the size of one step
Try these two loops at the prompt. The colon lets several instructions share a line. The semicolon after J keeps the numbers on the same row.
FOR J=3 TO 1 STEP -1:PRINT J;:NEXT J
FOR J=2 TO 6 STEP 2:PRINT J;:NEXT J
The first loop prints 3 2 1. The second prints 2 4 6. In RATIONS, NEXT used the usual step of one. Here you chose the size and direction. The end value belongs to the loop when the step lands on it.
For another kind of number question, try PRINT ABS(-3);INT(6.5). The results are 3 and 6. ABS measures how far a number is from zero. INT takes the greatest whole number at or below its input. For other built-in number tools, the language reference gives each one’s inputs and result. The next flight has an arithmetic problem you can catch with a watch.