ProgrammingVery hard

Which is the correct way to count distinct keys in a sorted struct array a[0..n-1] (n >= 1) by key?

  1. A. count = 1; for (i = 1; i < n; i++) if (a[i].key != a[i - 1].key) count++;
  2. B. count = 0; for (i = 0; i < n; i++) if (a[i].key != a[i + 1].key) count++;
  3. C. count = n; for (i = 1; i < n; i++) if (a[i].key == a[i - 1].key) count--;
  4. D. count = 1; for (i = 0; i < n; i++) if (a[i].key > a[i + 1].key) count++;

Correct answer: A. count = 1; for (i = 1; i < n; i++) if (a[i].key != a[i - 1].key) count++;

The first record always starts a group, so count begins at 1. Each new key differing from its predecessor adds one. The other versions read past the array or count the wrong thing.

More C Programming questions

Exams that ask this topic