Learn AP Comp Sci

Problem of the Day

Tuesday, November 25, 2025


Problem:

Two software developers are working on a snippet of code that is intended to calculate the average of an array of integers nums, and each produces code that passes all tests.

Code 1, from Programmer 1

int f = 0;
for (int r : nums) f += r;
double j = f == 0 ? 0 : f / nums.length;

Code 2, from Programmer 2

int sum = 0;
double average = 0;
for (int num : nums)
sum += num;
if (nums.length == 0)
average = 0;
else
average = sum / nums.length;

Which programmer's code is better, and why?

  1. Code 1 is better because it's shorter and takes up less space in memory
  2. Code 2 is better because the variable names make sense
  3. Code 1 is better because it uses a ternary operator in its third line
  4. Code 2 is better because it uses fewer variables

Show solution:

The correct answer is b. Although each program works as far as the computer is concerned, well-written code should be more-or-less readily understandable (and readable) by a reasonably experienced programmer who examines that code. Using good variable names is an important part of making a program readable.

Code 1, although shorter by a few lines of source code, won't be significantly longer when compiled into bytecode. The ternary operation in the last line of Code 1 is cool and that structure is understandable to most experienced programmers, but it doesn't change the fact that Code 2 is more legible.