edited by
975 views
6 votes
6 votes

What will be output printed by the following program?

#include<stdio.h>
main()
{
    int c=4;
    switch(c)
    {
        c=c-1;

        case 4:
            printf("IITB ");
            break;
        default:
            printf("IISc ");
        case 3:
            printf("IITM ");
        case 2 :
            printf("IITD");
    }
}

 

  1. $\text{IITB IITM}$
  2. $\text{IITB IISc IITM}$
  3. $\text{IITB}$
  4. $\text{IITB IITM IITD}$
edited by

4 Answers

8 votes
8 votes
$c=c-1;$

This statement is outside all cases (including default case) hence it will not get executed.

There is a break statement in case $4$ hence only case $4$ gets executed.
1 votes
1 votes

Here switch case is executed based on the value provided by $c=4$ in the given program. Now controls come to switch(4). Based on the value it will execute the statements associated with it. one more point here is the break keyword, this keyword is used to stop the execution of the program inside the switch block.

  1. Option (A) is wrong here because after printing IITB there is a break so IITM will not be printed.
  2. Option (B) is wrong because the default case is only executed if no case is matching but here switch(4) will print IITB but after that, there is a break so IISc will not be printed.
  3. switch(4) is match and print IITB as output.
  4. Option (D) is also wrong after IITB IITM can not be printed.

So Option (C) is correct.

Ref: switch Statement (C)

0 votes
0 votes

Answer:- In the given program, despite the statement c = c - 1; being placed before case 4, it doesn't affect the control flow within the switch statement. When the switch statement is evaluated, it checks the value of c, which is 4. As c matches case 4, "IITB" is printed. The invalid assignment c = c - 1; doesn't change the control flow because assignments within a switch block are not valid. Therefore, despite the presence of the invalid statement, "IITB" is printed.

Answer:

Related questions