Question
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?
Official answer and solution
- Official answer
- B
- From
- Official GATE 2021 answer key
Solution
Trace the loop while carefully applying short-circuit evaluation of the logical AND operator and post-increment side effects.
Initially, count = 0 and i = 0. The loop runs for .
In C, (j >= 0) && (i++) evaluates left-to-right with short-circuiting:
- :
j >= 0is false (0). The right operand(i++)is not evaluated.iremains 0. - :
j >= 0is false.iremains 0. - :
j >= 0is false.iremains 0. - :
j >= 0is true (1). Right operand(i++)evaluates to the current value ofi, which is 0 (false), and theniincrements to 1. Because the condition evaluates to false,count = count + jdoes not execute.
- :
j >= 0is true.(i++)evaluates to 1 (true) andibecomes 2. Since condition is true,count = count + j = 0 + 1 = 1. - :
j >= 0is true.(i++)evaluates to 2 (true) andibecomes 3.count = count + j = 1 + 2 = 3. - :
j >= 0is true.(i++)evaluates to 3 (true) andibecomes 4.count = count + j = 3 + 3 = 6.
After the loop finishes, count = count + i = 6 + 4 = 10. The statement printf("%d", count); outputs 10, matching option B.
B
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2021 Computer Science and Information Technology (CS, Set-1)
- Question
- 47 of 65, printed as CS Q.37
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.