GATE | Gate IT 2008 | Question 49
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
Answer: (C)
Explanation: Be careful about the scope of i,
there are two variables named: i, with different scope.
There are 2 main points to consider while solving this question. Scope of variable i and integer division.
First for loop will run for i = 0, 2 and 4 as i is incremented twice inside loop and resultant array will be a = 2, 2, 4, 4, 5, 6, 7, 8 (Loop will terminate at i = 4)
After that i value is 3 as there is a decrement operation after for loop.
Next for loop is running for j = 7, 6 and 5 and corresponding i values which is a local variable inside for loop will be 3 (7/2), 3 (6/2) and 2 (5/2). Array after this for loop will be
a = 2, 2, 3, 2, 5, 6, 7, 8
After the for loop, current i value is 3 and element at a[3] = 2.
This solution is contributed by Pranjul Ahuja.
Recommended Posts:
- GATE | GATE CS 2008 | Question 76
- GATE | GATE CS 2008 | Question 85
- GATE | GATE CS 2008 | Question 64
- GATE | GATE CS 2008 | Question 63
- GATE | GATE CS 2008 | Question 62
- GATE | GATE CS 2008 | Question 61
- GATE | GATE CS 2008 | Question 85
- GATE | GATE CS 2008 | Question 59
- GATE | GATE CS 2008 | Question 58
- GATE | GATE CS 2008 | Question 85
- GATE | GATE CS 2008 | Question 56
- GATE | GATE CS 2008 | Question 55
- GATE | GATE CS 2008 | Question 54
- GATE | GATE CS 2008 | Question 53
- GATE | GATE CS 2008 | Question 10



