ProgrammingVery hardProduct company OA

What is printed?

What is printed?
char s[] = "aaabccdddd";
char *r = s, *w = s;
while (*r) {
    char c = *r; int n = 0;
    while (*r == c) { r++; n++; }
    *w++ = c;
    if (n > 1) *w++ = (char)('0' + n);
}
*w = '\0';
printf("%s %td", s, w - s);
  1. A. a3bc2d4 7
  2. B. a3b1c2d4 8
  3. C. a3bc2d4 10
  4. D. abcd 4

Correct answer: A. a3bc2d4 7

A read pointer r scans runs and a write pointer w compresses in place; w can never overtake r because a run of length n writes at most min(n, 2) characters. Runs: aaa → 'a3', b → 'b' (no count for a single), cc → 'c2', dddd → 'd4'. The explicit terminator at w cuts off the stale tail, so the string is a3bc2d4 and w − s = 7. The inner loop stops at '\0' on its own because '\0' never equals c.

More C Programming questions

Exams that ask this topic