Output of C programs | Set 30 (Switch Case)
Prerequisite – Switch Case in C/C++
Interesting Problems of Switch statement in C/C++
-
Program 1
#include <stdio.h>
int
main()
{
int
num = 2;
switch
(num + 2)
{
case
1:
printf
(
"Case 1: "
);
case
2:
printf
(
"Case 2: "
);
case
3:
printf
(
"Case 3: "
);
default
:
printf
(
"Default: "
);
}
return
0;
}
Output:
Default:
Explanation: In switch, an expression “num+2” where num value is 2 and after addition the expression result is 4. Since there is no case defined with value 4 the default case got executed.
-
Program 2
#include<stdio.h>
void
main()
{
int
movie = 1;
switch
(movie << (2 + movie))
{
default
:
printf
(
" Traffic"
);
case
4:
printf
(
" Sultan"
);
case
5:
printf
(
" Dangal"
);
case
8:
printf
(
" Bahubali"
);
}
}
Output:
Bahubali
Explanation: We can write case statement in any order including the default case. That default case may be first case, last case or in between the any case in the switch case statement. The value of expression “movie << (2 + movie)" is 8.
-
Program 3
#include<stdio.h>
#define L 10
void
main()
{
auto
a = 10;
switch
(a, a*2)
{
case
L:
printf
(
"ABC"
);
break
;
case
L*2:
printf
(
"XYZ"
);
break
;
case
L*3:
printf
(
"PQR"
);
break
;
default
:
printf
(
"MNO"
);
case
L*4:
printf
(
"www"
);
break
;
}
}
Output:
XYZ
Explanation: In C, comma is also operator with least precedence. So if
x = (a, b);
Then x = b
Note: Case expression can be macro constant. -
Program 4
#include<stdio.h>
void
main()
{
switch
(2)
{
case
1L:
printf
(
"No"
);
case
2L:
printf
(
"%s"
,
"GEEKS"
);
goto
Love;
case
3L:
printf
(
"Please"
);
case
4L:Love:
printf
(
"FOR"
);
}
}
Output:
GEEKSFOR
Explanation: It is possible to write label of goto statement in the case of switch case statement.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...