in Programming in C edited by
22,341 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 _______.

in Programming in C edited by
22.3k views

4 Comments

how the different cases have chosen when the loop is executed?
0
0

Important point -->

'*'  and '/'  have the same precedence and are always executed left to right. https://stackoverflow.com/questions/21500961/which-has-higher-precedence-in-c-multiplication-or-division

11
11
1,1,3,3,2   =10
1
1
correct
0
0

1 Answer

133 votes
133 votes
Best answer
 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

4 Comments

@dileepbhagat2196 you are wrong. You should know precedence and Associativity rule for this question. * and / are of same precedence but Associativity is left to right so first 2*3 will be solved. So (2*3)/4= 6/4= 1

0
0
Pl can anybody tell me, why for i = 2   case 2, case 3, and default will be executed?

got it thank u
0
0
Excellent explanation
0
0
Answer:

Related questions