问题
I've got a student studying for the AP CS test (he takes it next week). I was hired mid/end year to basically be a long term sub for the rest of the school year for these IT classes. I don't know enough about java or programming to explain to him why the answer to this practice test problem is B and not A (according to the answer sheet).
I'm hoping this might be a decent place to get an explanation I can take to him...
/** Precondition: arr contains only positive values.
*/
public static void doSome(int[]arr, int lim)
{
int v = 0;
int k = 0;
while (k < arr.length && arr[k] < lim)
{
if (arr[k] > v)
{
v = arr[k]; /* Statement S */
}
k++; /* Statement T */
}
}
Assume that doSome is called and executes without error. Which of the following are possible combinations for the value of lim, the number of times Statement S is executed, and the number of times Statement T is executed?
possible combinations for the value of lim

(A) I only
(B) II only
(C) III only
(D) I and III only
(E) II and III only
回答1:
III is not a valid combination because you can't execute S more times than you execute T.
From a test-taking perspective: In this problem, this is the most important insight because figuring this out immediately knocks out 3 options and takes you down to a 50/50 shot on a guess.
I is not a valid combination because the array contains only positive values, all of which are > 0, so the conditional if(arr[k]>v) must return true at least once, meaning that S is executed at least once if the while loop body gets executed at least once. In option I, statement T (also in the body of the while loop) is executed 5 times, so S must be executed at least once.
II is a valid combination of values.
From a test-taking perspective: It's not worth taking the time to prove this (e.g. by providing sample inputs that produce this combination), as process of elimination has already taken you down to one answer.
Therefore, option B, II only, is the correct answer.
Props to the AP test question writer.
来源:https://stackoverflow.com/questions/36904173/practice-ap-cs-test