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: printf("j=%d\n", j); case 2: printf("j=%d\n", j); } } return 0; } The number of times printf statement is executed is _______.
GATE 2015 · Programming and Data Structures · Switch Case · medium
Answer: The printf statement is executed 3 times.
- Compute j: 2*3 = 6; 6/4 = 1 (integer division). 2.0/5 = 0.4 (float). 8/5 = 1 (integer division). Sum = 1 + 0.4 + 1 = 2.4. Since j is int, j = 2 (truncation).
- Compute k: --j: j goes from 2 to 1. k -= j means k = 0 - 1 = -1. After: j=1, k=-1.
- Trace the loop iterations: i=0: switch(-1) -> no match -> 0 printfs. i=1: switch(0) -> no match -> 0 printfs. i=2: switch(1) -> matches case 1, prints 'j=1'; no break, falls to case 2, prints 'j=1'. 2 printfs. i=3: switch(2) -> matches case 2, prints 'j=1'. 1 printf. i=4: switch(3) -> no match -> 0 printfs.
- Total count: Total printf executions = 0 + 0 + 2 + 1 + 0 = 3.