Question 14
A program reads a data file containing city names and their populations. The following code segment is intended to find the city with the largest population.
maxPop <- 0
maxCity <- ""
FOR EACH row IN cityData
{
IF(row[2] > maxPop)
{
maxPop <- row[2]
maxCity <- row[1]
}
}
DISPLAY(maxCity)
The data file contains the following entries:
| City | Population |
| Riverside | 320000 |
| Lakewood | 185000 |
| Hillcrest | 475000 |
| Oakdale | 290000 |
What is displayed when the code segment is executed?
- ARiverside
- BLakewood
- CHillcrest
- DOakdale
Show answer and explanation
Answer: C
The code initializes maxPop to 0 and iterates through each row. For Riverside, 320000 > 0 is true, so maxPop becomes 320000 and maxCity becomes Riverside. For Lakewood, 185000 > 320000 is false. For Hillcrest, 475000 > 320000 is true, so maxPop becomes 475000 and maxCity becomes Hillcrest. For Oakdale, 290000 > 475000 is false. The final displayed value is Hillcrest, the city with the largest population.