Consider the C program given below. What does it print? #include <stdio.h> int…
2008
Consider the C program given below. What does it print?
#include <stdio.h>
int main ()
{
int i, j;
int a [8] = {1, 2, 3, 4, 5, 6, 7, 8};
for(i = 0; i < 3; i++) {
a[i] = a[i] + 1;
i++;
}
i--;
for (j = 7; j > 4; j--) {
int i = j/2;
a[i] = a[i] - 1;
}
printf ("%d, %d", i, a[i]);
}
/* Add code here. Remove these lines if not writing code */
- A.
2, 3
- B.
2, 4
- C.
3, 2
- D.
3, 3
Attempted by 8 students.
Show answer & explanation
Correct answer: C
Step-by-step execution
Initial state: array a = {1, 2, 3, 4, 5, 6, 7, 8}, and i starts at 0.
First for loop: for(i = 0; i < 3; i++) { a[i] = a[i] + 1; i++; }
Iteration 1: i = 0 → a[0] becomes 2. The i++ inside the body makes i = 1, then the for-loop increment makes i = 2.
Iteration 2: i = 2 → a[2] becomes 4. The i++ inside the body makes i = 3, then the for-loop increment makes i = 4. Loop ends because i >= 3.
After the loop i-- executes, so outer i becomes 3. Array now is a = {2, 2, 4, 4, 5, 6, 7, 8}.
Second for loop: for (j = 7; j > 4; j--) { int i = j/2; a[i] = a[i] - 1; }
j = 7 → inner i = 7/2 = 3 → a[3] becomes 4 - 1 = 3.
j = 6 → inner i = 6/2 = 3 → a[3] becomes 3 - 1 = 2.
j = 5 → inner i = 5/2 = 2 → a[2] becomes 4 - 1 = 3.
Note: the inner declaration int i = j/2; creates a new i that shadows the outer i, so the outer i is unchanged by these assignments.
After this loop the array is a = {2, 2, 3, 2, 5, 6, 7, 8} and the outer i is still 3.
The final printf prints the outer i and a[i]: printf("%d, %d", i, a[i]); prints 3, 2.
Final output: 3, 2