edited by
22,297 views
77 votes
77 votes

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

edited by

1 Answer

Best answer
133 votes
133 votes
 j=2 * 3 / 4 + 2.0 / 5 + 8 / 5;

$j = (((2 * 3) / 4) + (2.0 / 5) ) + (8/5)$; //As associativity of $+,*$ and $/$ are from left to right and $+$ has less precedence than $*$ and $/$.

$j = ((6/4) + 0.4) + 1);$ //$2.0$ is double value and hence $5$ is implicitly typecast to double and we get $0.4$. But $8$ and $5$ are integers and hence $8/5$ gives $1$ and not $1.6$

$j = (1 + 0.4) + 1$; // $6/4$ also gives $1$ as both are integers

$j = 1.4 + 1$; //$1 + 0.4$ gives $1.4$ as $1$ will be implicitly typecast to $1.4$

$j = 2.4$; // since $j$ is integer when we assign $2.4$ to it, it will be implicitly typecast to int.

So, $j = 2$;

$k -= --j$;

This makes $j = 1$ and $k = -1$.

The variables $j$ and $k$ have values $1$ and $-1$ respectively before the for loop. Inside the for loop, the variable $i$ is initialized to $0$ and the loop runs from $0$ to $4$.

$i=0, k=-1, i+k=-1$, default case is executed, printf $count = 1$

$i=1, k=-1, i+k=0$, default case is executed, printf $count = 2$

$i=2, k=-1, i+k=1$, case 2, case 3 and default case is executed, printf $count = 5$

$i=3, k=-1, i+k=2$, case 2, case 3 and default case is executed, printf $count = 8$

$i=4, k=-1, i+k=3$, case 3 and default case is executed, printf $count = 10$

$i=5$, loop exits and the control returns to main

Answer is 10.

edited by
Answer:

Related questions

62 votes
62 votes
11 answers
2
47 votes
47 votes
8 answers
3
go_editor asked Feb 14, 2015
15,858 views
Consider the following C program segment.# include <stdio.h int main() { char s1[7] = "1234", *p; p = s1 + 2; *p = '0'; printf("%s", s1); }What will be printed by the pro...
3 votes
3 votes
2 answers
4