Chap 3 Switch Case Statements
Chap 3 Switch Case Statements
is given below:
1. switch(expression)
2. {
3. case value1:
4. //code to be executed;
5. break; //optional
6. case value2:
7. //code to be executed;
8. break; //optional
9. ......
10. default:
11. //code to be executed if all cases are not matched;
12. }
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
When the above code is compiled and executed, it produces the following result
Well done
Your grade is B
Switch case example 2
#include <stdio.h>
int main()
{
int x = 10, y = 5;
switch(x>y && x+y>0)
{
case 1:
printf("hi");
break;
case 0:
printf("bye");
break;
default:
printf(" Hello bye ");
}
Output
hi
In C language, the switch statement is fall through; it means if you don't use a
break statement in the switch case, all the cases after the matching case will be
executed.
Let's try to understand the fall through state of switch statement by the example
given below.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
Nested switch case statement
We can use as many switch statement as we want inside a switch statement. Such type
of statements is called nested switch case statements. Consider the following example.
1. #include <stdio.h>
2. int main () {
3.
4. int i = 10;
5. int j = 20;
6.
7. switch(i) {
8.
9. case 10:
10. printf("the value of i evaluated in outer switch: %d\n"
,i);
11. case 20:
12. switch(j) {
13. case 20:
14. printf("The value of j evaluated in nested switch:
%d\n",j);
15. }
16. }
17.
18. printf("Exact value of i is : %d\n", i );
19. printf("Exact value of j is : %d\n", j );
20.
21. return 0;
22. }
Output
the value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of i is : 10
Exact value of j is : 20
Practice Problems:
70-100 Distinction
60-69 First Class
50-59 Second Class
40-49 Pass Class
0-39 Fail