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.

  1. 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 =1+0.4+1=2.4= 1 + 0.4 + 1 = 2.4
    • Assigning 2.4 to integer j truncates to j=2j = 2.
  1. Evaluate k -= --j:
    • Pre-decrement --j decrements j from 2 to 1 and returns 1.
    • k -= 1 sets k=0−1=−1k = 0 - 1 = -1.
  1. Loop for (i = 0; i < 5; i++) with k=−1k = -1:
    The switch expression is i+k=i−1i + k = i - 1:
    • i=0i = 0: i+k=−1i + k = -1. Matches default, executing 1 printf.
    • i=1i = 1: i+k=0i + k = 0. Matches default, executing 1 printf.
    • i=2i = 2: i+k=1i + k = 1. Matches case 1: (no break), falls through to case 2: printf, falls through to case 3: printf, falls through to default: printf. Executes 3 printf calls.
    • i=3i = 3: i+k=2i + k = 2. Matches case 2: printf, falls through to case 3: printf, falls through to default: printf. Executes 3 printf calls.
    • i=4i = 4: i+k=3i + k = 3. Matches case 3: printf, falls through to default: printf. Executes 2 printf calls.

Total number of times printf is executed =1+1+3+3+2=10= 1 + 1 + 3 + 3 + 2 = 10.

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.