Small Steps III — Thinking with Programs
Counting occurrences of the largest value
Count occurrences of the largest value.
What you will learn
Combining two procedures you already know can solve a new problem.
Try it
Example · example2.cpp
void small_main()
{
Array<int> numbers = {4, 9, 2, 9, 7};
int largest = numbers[0];
int count_largest = 0;
for (int i = 0; i < numbers.length(); i = i + 1)
if (numbers[i] > largest)
largest = numbers[i];
for (int i = 0; i < numbers.length(); i = i + 1)
if (numbers[i] == largest)
count_largest = count_largest + 1;
print("Largest: ", largest);
print("How many: ", count_largest);
}
First find the maximum, then use a second loop to count elements equal to it. The output is Largest: 9 and How many: 2.
Make each step's responsibility clear before trying to combine the two loops. The array must contain at least one element.
Exercise
First find the Array's largest value, then count how often it occurs in a second loop.
Exercise starter · exercise2_starter.cpp
void small_main()
{
Array<int> numbers = {5, 9, 2, 9, 9, 4};
// find largest, then count it.
}
Hint
The first loop finds largest; the second counts occurrences of numbers[i] == largest.
show solution
void small_main()
{
Array<int> numbers = {5, 9, 2, 9, 9, 4};
int largest = numbers[0];
for (int i = 1; i < numbers.length(); i = i + 1)
if (numbers[i] > largest)
largest = numbers[i];
int count = 0;
for (int i = 0; i < numbers.length(); i = i + 1)
if (numbers[i] == largest)
count = count + 1;
print("Largest: ", largest);
print("Count: ", count);
}