GATE / CS ARCHIVE

SIMILAR QUESTIONS / PROGRAMMING IN C

Trace and count switch fall-through output

2 questions solved the same way, newest first. Back to Programming in C

How these are solved

Enter at the matching label and execute subsequent statements through default unless a break intervenes; neither program supplies breaks. The 2012 fixed-character case asks text output, with source escape/typography caveats;

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

1 mark · MCQ
Report issue

Switch fall-through and escape sequences

Control Flow & Loop Tracing

Question 3, GATE 2012: What will be the output of the following C program segment?

       char inChar = ‘A’ ;
       switch ( inChar ) {
       case ‘A’ : printf (“Choice A\ n”) ;
       case ‘B’ :
       case ‘C’ : printf (“Choice B”) ;
       case ‘D’ :
       case ‘E’ :
       default : printf ( “ No Choice” ) ; }
       (A) No Choice
       (B) Choice A
       (C) Choice A
            Choice B No Choice
       (D) Program gives no output as it is erroneous
Tap to enlarge
Your answer
Answer & solution

Official answer: Marks to All

Our answer: C under intended newline interpretation

If the first printf is interpreted as the intended standard newline escape \n, execution enters case A and falls through every following label because there is no break. It prints Choice A, a newline, then Choice B and No Choice, matching C. The printed source visibly separates the backslash and n in the first string; taking backslash-space literally is not the standard newline escape and does not justify an unconditional portable-output answer. The official key awards Marks to All. This is an independently observed printing/interpretation concern, not a claim about the authority’s reason.

Check: Switch labels are entry points, not implicit stopping points. After executing the case-A printf, the empty B label passes through to C’s printf; D and E are also empty, so execution reaches default’s printf before leaving the switch.

Original paper, page 2 · Answer key