ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
int find(const char *hay, const char *nd) {
    for (const char *p = hay; *p; p++) {
        const char *a = p, *b = nd;
        while (*b && *a == *b) { a++; b++; }
        if (!*b) return (int)(p - hay);
    }
    return -1;
}
int main(void) {
    printf("%d", find("abcabcd", "cd"));
}
  1. A. 2
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: C. 5

The search checks each start position, and the first position where cd matches is index 5, the c before d. The first c at index 2 is followed by a, so it does not match.

More C Programming questions

Exams that ask this topic