Chapter 5 - Arrays
Exercise 2: Counting Occurrences
We’ve set up a small array that contains the numbers 0, 1, and 2, each repeated a random number of times. Update the program to count how many times each number occurs.
Hint: You can set up a second array to keep track of the number of occurrences. A three-element array will (conveniently) have the indexes 0, 1, and 2…
Solution
Output:
0 occurred 4 times
1 occurred 3 times
2 occurred 2 times
Extra credit:
Output:
0 occurred 11 times
1 occurred 12 times
2 occurred 10 times
3 occurred 7 times
4 occurred 12 times
5 occurred 10 times
6 occurred 8 times
7 occurred 9 times
8 occurred 11 times
9 occurred 10 times