Question
Consider the following C program:
#include <stdio.h>
int main()
{
int i, j, k = 0;
j = 2 * 3 / 4 + 2.0 / 5 + 8 / 5;
k -= --j;
for (i = 0; i < 5; i++)
{
switch (i + k)
{
case 1:
case 2: printf("\n%d", i + k);
case 3: printf("\n%d", i + k);
default: printf("\n%d", i + k);
}
}
return 0;
}
The number of times printf statement is executed is _____.
Official answer and solution
- Official answer
- 10
- From
- Official GATE 2015 answer key
Solution
Trace arithmetic evaluation, pre-decrement operator, and switch-case fall-through behavior.
- Evaluate
j = 2 * 3 / 4 + 2.0 / 5 + 8 / 5:2 * 3 / 4:6 / 4 = 1(integer division)2.0 / 5:0.4(floating point division)8 / 5:1(integer division)- Sum
- Assigning
2.4to integerjtruncates to .
- Evaluate
k -= --j:- Pre-decrement
--jdecrementsjfrom 2 to 1 and returns 1. k -= 1sets .
- Pre-decrement
- Loop
for (i = 0; i < 5; i++)with :
The switch expression is :- : . Matches
default, executing 1printf. - : . Matches
default, executing 1printf. - : . Matches
case 1:(no break), falls through tocase 2: printf, falls through tocase 3: printf, falls through todefault: printf. Executes 3printfcalls. - : . Matches
case 2: printf, falls through tocase 3: printf, falls through todefault: printf. Executes 3printfcalls. - : . Matches
case 3: printf, falls through todefault: printf. Executes 2printfcalls.
- : . Matches
Total number of times printf is executed .
Final answer
10
Common trap
Forgetting that switch statements without break fall through to all subsequent cases including default.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 3
- Question
- 58 of 65, printed as CS Q.48
- 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.