ProgrammingHard
char b[5]; /* stdin holds the nine bytes: abcdefgh and a newline */ int calls = 0; do { fgets(b, sizeof b, stdin); calls++; } while (b[strlen(b) - 1] != '\n'); printf("%d", calls); How many times does the loop body run?
- A. 2
- B. 3
- C. 4
- D. 5
Correct answer: B. 3
fgets with size 5 reads at most 4 characters per call, so the input arrives as 'abcd', 'efgh' and finally a lone newline. The loop ends on the third call, when the last character is a newline.
More C Programming questions
- char s[] = "a,,b,c"; int n = 0; for (char t = strtok(s, ","); t != NULL; t = strtok(NULL, ",")) n++; printf("%d", n); What is printed?
- char d[8] = "ab"; strncat(d, "cdefgh", 3); printf("%zu", strlen(d)); What is printed?
- Which statement about the value returned by strcmp("apple", "Apple") is guaranteed by the C standard?
- char s[] = "abcdef"; memmove(s + 2, s, 4); printf("%s", s); What is printed?
- char a[10] = "hi"; printf("%zu", sizeof(a) - strlen(a) - 1); What is printed?
- char s[] = "xyz"; char p = s; p[0] = 'a'; printf("%s %zu", s, sizeof s); What is printed?