Practice AP CS Test

此生再无相见时 提交于 2021-02-19 08:19:06

问题


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

Image of 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!