What will be the output of the program given below?
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
What will be the output of the program given below?
#include <stdio.h>
int main()
{
int a[6] = {2, 3, 4, 5, 6, 7};
int i;
for (i = 0; i < 5; i++);
{
printf("%d", *(&a[i]));
printf(" %d %d %d %d", a[i], i[a], *(a + i), *(i + a));
}
return 0;
}
Show answer & explanation
Answer: A. 7 7 7 7 7
The critical issue is the semicolon after the for loop: for (i = 0; i < 5; i++);. This creates an empty loop body, so the loop executes 5 times without doing anything, leaving i = 5 after the loop completes. The printf statements are not part of the loop—they execute only once with i = 5. All five expressions evaluate to a[5] = 7: *(&a[5]) = 7, a[5] = 7, 5[a] = 7 (array subscripting is commutative), *(a+5) = 7, and *(5+a) = 7. The output is a single line: 7 7 7 7 7.
Step-by-step Derivation:
- The for loop has a semicolon at the end:
for (i = 0; i < 5; i++);— this is a null statement. - The loop body is empty. The loop runs 5 times (i goes from 0 to 4, then i++ makes it 5, then condition i < 5 fails).
- After the loop, i = 5.
- The printf statements are NOT inside the loop (no braces after the for loop). They execute once.
- Evaluation with i = 5:
- *(&a[5]) = a[5] = 7
- a[5] = 7
- i[a] = a[i] = a[5] = 7 (subscripting is commutative in C: a[i] ≡ *(a+i) ≡ *(i+a) ≡ i[a])
- *(a + 5) = 7
- *(5 + a) = 7
- Output:
7 7 7 7 7