- Consider the following program segment:
/** Precondition: a[0]...a[n-1] is an initialized array of integers, and 0 < n <= a.length. **/
int c = 0;
for (int i = 0; i < n; i++)
if (a[i] >= 0)
{
a[c] = a[i];
c++;
}
n = c;
Which is the best postcondition for the segment?
- a[0] to a[n-1] has been stripped of all positive integers.
- a[0] to a[n-1] has been stripped of all negative integers.
- a[0] to a[n-1] has been stripped of all nonnegative integers.
- 4a[0] to a[n-1] has been stripped of all occurrences of zero.
- The updated value of n is less than or equal to the value of n before execution of the segment.
This is a question on the AP CSA exam. The answer key says that 2. is the answer (it states that 5. is also correct but would not be the "best" postcondition). But I am just thinking: "what if ALL the elements in the initial list are negative numbers?" If that's the case, wouldn't it be impossible to strip away any negative number?