Consider the following C program: #include int main( ) { int i, j, k = 0; j = 2 * 3 / 4 + 2.0 / 5 + 8 / 5; k -= --j; for(i = 0; i The number of times printf statement is executed is …
Topic-wise GATE CS PYQs with verified steps
GATE CSE 2015 Set 3 · Q48
Time
#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("
%d", i+k);
case 3: printf("
%d", i+k);
default: printf("
%d", i+k);
}
}
return 0;
}The number of times printf statement is executed is _________.Your answerNumerical answer
Solution
Official answer: 10
Programming in CLet us trace the program step-by-step:
Evaluation of j:
2 * 3 / 4 involves integer arithmetic: .
2.0 / 5 involves floating-point arithmetic: .
8 / 5 involves integer arithmetic: .
The expression evaluates to .
Since j is of type int, it is truncated to 2.
Evaluation of k:
k -= --j; first decrements j from 2 to 1 (pre-decrement), so --j evaluates to 1.
k = k - 1 = 0 - 1 = -1.
Loop execution (i = 0 to 4):
Note that the switch statement has no break statements, so execution falls through from matching cases.
i = 0: i + k = -1. Matches default:, executing printf1 time.
i = 1: i + k = 0. Matches default:, executing printf1 time.
i = 2: i + k = 1. Matches case 1:, falls through to case 2, case 3, and default, executing printf3 times.
i = 3: i + k = 2. Matches case 2:, falls through to case 3 and default, executing printf3 times.
i = 4: i + k = 3. Matches case 3:, falls through to default, executing printf2 times.
Total printf executions:
Thus, the printf statement is executed 10 times.
Try the question first, then check your work.
Examiner trap
Evaluate the arithmetic expression considering integer division and type coercion, and remember that cases without a break statement will fall through.
This Programming in C previous year question is Q48 of the GATE CSE 2015 Set 3 paper. Find more GATE CSE PYQs on Programming in C in Programming and Data Structures, or browse all GATE CSE PYQs.
Free diagnostic
Take the 20-minute diagnostic: the 3 topics that cost you the most marks, and a rank range. Or sit 5 related Programming in C PYQs now with no account.
An official question by email at 7 AM IST, with a link to its verified solution. Unsubscribe in one click.
Programming in C has 74 GATE CSE PYQs across 25 papers from 2011 to 2026. 17 of them are 2-mark NAT questions like this one, and GATE CSE 2015 Set 3 has 4.
How GATE tests Programming in CIndependent practice explanation verified by the GateAI team. GATE is conducted by the IITs; question text follows the official paper.