The following C function takes two ASCII strings and determines whether one is…

2005

The following C function takes two ASCII strings and determines whether one is an anagram of the other. An anagram of a string s is a string obtained by permuting the letters in s.

int anagram (char *a, char *b) {
int count [128], j;
for (j = 0;  j < 128; j++) count[j] = 0;
j = 0;
while (a[j] && b[j]) {
A;
B;
}
for (j = 0; j < 128; j++) if (count [j]) return 0;
return 1;
}

Choose the correct alternative for statements A and B.

  1. A.

    A : count [a[j]]++ and B : count[b[j]]--

  2. B.

    A : count [a[j]]++ and B : count[b[j]]++

  3. C.

    A : count [a[j++]]++ and B : count[b[j]]--

  4. D.

    A : count [a[j]]++and B : count[b[j++]]--

Attempted by 5 students.

Show answer & explanation

Correct answer: D

Correct replacements for the two statements inside the loop are:

count[a[j]]++;

count[b[j++]]--;

Why this works:

  • Initialization: The count array starts at zero for all ASCII codes.

  • Per-iteration effect: For the same index j, incrementing count for the character from the first string and decrementing for the character from the second string causes matching characters to cancel.

  • Index advancement: Using post-increment on the second access advances j exactly once per loop iteration, ensuring both strings are processed synchronously.

  • Final check: After the loop, scanning the count array for any nonzero entry detects differences in character multiset or unequal lengths; if all are zero, the strings are anagrams.

Common mistakes and why they fail:

  • Not advancing j inside the loop keeps processing the same position and leads to an infinite loop.

  • Incrementing counts for both strings (instead of incrementing one and decrementing the other) prevents cancellation and makes the final zero-check fail.

  • Advancing j between the two accesses (so they use different indices) misaligns characters from the two strings and yields incorrect results.

Summary: Use count[a[j]]++; followed by count[b[j++]]--; so both characters at the same index are processed and j is advanced exactly once per iteration; afterwards verify all counts are zero to confirm an anagram.

Explore the full course: Gate Guidance By Sanchit Sir