Difficulty: Medium
Correct Answer: mmmm aaaa nnnn
Explanation:
Introduction / Context:
This question checks your understanding of how array indexing and pointer arithmetic work in C, including the less common but valid notation i[s]. The code uses several equivalent expressions to access the same character in a string. Understanding that all four expressions refer to the same element explains why the output repeats the same character four times on each line.
Given Data / Assumptions:
Concept / Approach:
In C, an array name such as s is converted to a pointer to its first element when used in an expression. The expression s[i] is defined as *(s + i). Pointer arithmetic allows i + s as well, so *(i + s) is equivalent to s[i] as well. C also defines a[b] as *(a + b), which means i[s] is just another spelling of *(i + s). Therefore, all four expressions in the printf call access the same character in the string for a given i. The loop runs once for each character m, a, and n, printing a newline followed by that character repeated four times.
Step-by-Step Solution:
Step 1: When i is zero, s[0] is m, so each of the four expressions yields m. The program prints a newline and then mmmm.Step 2: When i is one, s[1] is a, and again each expression refers to that character. The program prints a newline and then aaaa.Step 3: When i is two, s[2] is n, so the line printed is nnnn.Step 4: When i becomes three, s[3] is the terminating zero character, so the loop condition s[i] is false and the loop terminates.Step 5: Combining the lines, the visible output is mmmm on the first printed line, aaaa on the second, and nnnn on the third. Option A summarizes this as mmmm aaaa nnnn.
Verification / Alternative check:
Writing a small test program and running it will show the same repeated characters for each line. You can also replace the printf call with separate prints of each expression to confirm that they always produce the same character. The key is to remember that C array indexing is defined in terms of pointer addition and dereferencing, giving several equivalent forms.
Why Other Options Are Wrong:
Option B suggests the order aaaa mmmm nnnn, which would require a different loop order or index values.Option C reverses the order in a way that does not match the character sequence in the string.Option D claims that nothing is printed, which is clearly false because the loop executes for three iterations.
Common Pitfalls:
Many learners are surprised that i[s] is valid C syntax. It is exactly equivalent to s[i] because a[b] is defined as *(a + b). Another pitfall is forgetting the terminating zero character, which controls loop termination. Understanding pointer arithmetic and array decay rules is crucial for mastering these kinds of questions.
Final Answer:
The correct answer is mmmm aaaa nnnn.
Discussion & Comments