GATE / CS ARCHIVE

GATE CSE 2015 SET 3 / QUESTION 53

GATE CSE 2015 Set 3 Q53

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2015 Set 3 paper

GATE 2015 Set 3, Q53 2 marks · NAT
Report issue

Control Flow & Loop Tracing

Question 53, GATE 2015: How many times is printf executed in this 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;
}
There are no break statements.
Tap to enlarge
Answer & solution

Official answer: 10

1. Integer division gives 2*3/4=1 and 8/5=1; adding 2.0/5 produces 2.4, converted to int j=2.

2. Then k-=--j sets j=1 and k=−1. For i=0, 1, 2, 3, 4 the switch values are−1, 0, 1, 2, 3. With no breaks, the numbers of printf executions are 1, 1, 3, 3, 2, totaling 10. Case1 falls into case2 without printing itself.

Original paper, page 74 · Answer key