What will be the output of the following C program segment? char inChar = ‘A’ ; switch ( inChar ) { case ‘A’ : printf (“Choice A\n”) ; case ‘B’ : case ‘C’ : printf (“Choice B”) ; case ‘D’ : case ‘E’ : default : printf ( “ No Choice” ) ; }
What will be the output of the following C program segment? char inChar = ‘A’ ; switch ( inChar ) { case ‘A’ : printf (“Choice A\n”) ; case ‘B’ : case ‘C’ : printf (“Choice B”) ; case ‘D’ : case ‘E’ : default : printf ( “ No Choice” ) ; } Correct Answer <p>Choice A</p> <p>Choice B No Choice</p>
The correct answer is "option 3".
CONCEPT:
The expression in switch condition is evaluated once and compared with values of each case value.
Also, the break statement is used to move the control out of the switch case after matching case statements gets executed.
If there is no match, then the default clause is used.
The default clause is optional
EXPLANATION:
char inChar = ‘A’ ;
// inChar variable having char datatype is initialized with value “A”.
switch ( inChar ) // switch condition is compared
case ‘A’: printf("Choice A\n");
// the case value is matched & statement gets executed but since there is no break it will move to case value B
case 'B':
//no statement & no break so it will move to case value C
case ‘C’: printf ("Choice B");
// print given statement & since no break so it will move to case value D
case 'D':
//no statement & no break so it will move to case value E
case 'E':
//no statement & no break so it will move to the default case
default: printf ( "No Choice" ) ; }
// print the statement and move out of the switch case.
So the output will be:
Choice A
Choice B No Choice
Hence the correct answer is "option 3".