GATE 2021 CS (CS1) – Question 47
Consider the following ANSI C program.
#include <stdio.h>
int main()
{
int i, j, count;
count = 0;
i = 0;
for (j = -3; j <= 3; j++)
{
if ((j >= 0) && (i++))
count = count + j;
}
count = count + i;
printf("%d", count);
return 0;
}Which one of the following options is correct?
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (B) The program will compile successfully and output 10 when executed.
Explanation
Trace the loop `for (j=-3; j<=3; j++)`; the condition `(j >= 0) && (i++)` increments `i` **only when `j >= 0`** (short-circuit evaluation).
| j | j>=0? | i++ evaluated? | value of i++ (old i) | count |
|---|---|---|---|---|
| -3, -2, -1 | no | no | 0 | |
| 0 | yes | yes | 0 (false); i becomes 1 | 0 |
| 1 | yes | yes | 1 (true); i becomes 2 | $+1=1$ |
| 2 | yes | yes | 2 (true); i becomes 3 | $+2=3$ |
| 3 | yes | yes | 3 (true); i becomes 4 | $+3=6$ |
After the loop `count = count + i = 6 + 4 = 10`. The output is **10**.