Using the Elements of an Array as Counters

Sometimes, programs use counter variables to summarize data, such as the results of a survey. Figure E.6 uses the array frequency (line 10) to count the occurrences of each side of the die that’s rolled 6,000,000 times. Line 14 uses the random value to determine which frequency element to increment during each iteration of the loop. The calculation in line 14 produces random numbers from 1 to 6, so the array frequency must be large enough to store six counters. However, we use a seven-element array in which we ignore frequency[0]—it’s more logical to have the face value 1 increment frequency[1] than frequency[0]. Thus, each face value is used as an index for array frequency. In line 14, the calculation ...

Get Android™ How to Program, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.