Skip to content
Official PYQ · 2015

GATE CS 2015 Set 3 Q48 — Programming in C

Explain with AI

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 _______.

View worked solution

Answer: 10

To find the number of times the printf statement is executed, we trace the program step-by-step:

Step 1: Calculate the initial values of jj and kk

  • 2 * 3 / 4 evaluates to 6 / 4 = 1 (integer division).
  • 2.0 / 5 evaluates to 0.4 (floating-point division).
  • 8 / 5 evaluates to 1 (integer division).
  • Thus, j=1+0.4+1=2.4j = 1 + 0.4 + 1 = 2.4. Since jj is of type int, it is truncated to 22.
  • Next, k -= --j decrements jj to 11 first, then k=0−1=−1k = 0 - 1 = -1.

Step 2: Trace the loop for i=0i = 0 to 44

The switch expression is i+k=i−1i + k = i - 1. Since there are no break statements, execution falls through to subsequent cases once a match is found:

ii i+ki + k Matching Case & Fall-through Path printf Executions
0 -1 default 1
1 0 default 1
2 1 case 1 → case 2 → case 3 → default 3
3 2 case 2 → case 3 → default 3
4 3 case 3 → default 2

Total Executions: 1+1+3+3+2=101 + 1 + 3 + 3 + 2 = 10.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions