Counting the Totals
Counting totals by eye doesn't scale. Meet the array — eleven counters in one named structure — and use the dice total itself as the index. One line tallies any roll, no chain of IFs. Twenty rolls in, the shape is still ragged.
Watching totals scroll past tells you they cluster, but to count them you'd need eleven
separate variables — one for each total from 2 to 12 — and eleven IFs to decide which to add
to. That's the moment for a new tool: the array. One name, eleven slots, and the dice total
picks the slot for you.
10 PRINT CHR$(147)
20 DIM T(12)
30 FOR I=1 TO 20
40 D=INT(RND(1)*6)+1+INT(RND(1)*6)+1
50 T(D)=T(D)+1
60 NEXT I
70 FOR F=2 TO 12
80 PRINT "TOTAL";F;"-";T(F)
90 NEXT F
DIM T(12) on line 20 sets up the array: a row of counters numbered 0 to 12, all starting at
zero. (You only use 2 to 12, and the spare low slots cost nothing.) The magic is line 50:
T(D) = T(D)+1. The total D is used as the index — roll a 9 and T(9) goes up by one;
roll a 7 and T(7) goes up. The value chooses its own counter. No IF, no testing — the
number does the filing.
This is what arrays are for: many values under one name, reached by a number. After the loop,
lines 70–90 walk F from 2 to 12 and print each count. But look at the figure — twenty rolls
is too few. The middle leads, but the shape is lumpy and some totals are still empty. The
pattern is there; it just needs more rolls to show itself.
Try this
- Check the sum. Add up all eleven counts — they should come to exactly 20, the number of rolls. Every roll landed in exactly one slot.
- One more total. The array runs to 12 because that's the highest two dice can make. What
would you change to tally three dice? (Hint: the top total, and the
DIM.)
What's next
Twenty rolls is too ragged to trust. In Unit 4 you roll a thousand — and the bell stops hiding and shows itself plainly in the numbers.