Examples of Switch Statements in C
For Complete YouTube Video: Click Here
In this class, Examples of Switch Statements in C.
We have already explained the concepts of if-else, Nested-if, if-else-if, switch selection statements.
Table of Contents
Examples of Switch Statements in C
Example 1
The image below is example 1 of switch statements in C.
In the above example, we have defined a variable “i” with a value of 65.
In the switch statement, we have provided “i,” which means wherever the case is 65, that case will get executed.
But we don’t have the case of 65 in our program.
What is the output o the program?
As we have discussed, the binary values of integers and ASCII codes get used interchangeably.
The corresponding ASCII codes of the integer equivalent, which is case A, will also get executed.
The point to understand is this is how the compiler will work.
Example 2:
The image below is example 2 of switch statements in C.
In the above example, the switch statement uses an expression.
Is it accepted, or will the compiler generate an error?
The switch statements can use an expression.
It is legal to use expressions in the switch statements.
The output of the expression is the case for which the compiler will search.
For example, we have given the values of x and y as 4 and 2.
The sum of x and y in the switch statement is six, and case 6 will get executed.
Example 3
The image below is example 3 of switch statements in C.
In the above example, we have defined two variables int x = 65 and char ch = ‘A.’
Here, we have to understand that both x and ch have the same binary value.
The cases in the switch statement have 65 and A.
Both the cases have the same binary value, so the compiler will consider them as duplicate values.
Duplicate cases are not allowed in the switch statements.
The compiler will generate an error.
Example 4
The image below is example 4 of switch statements in C.
In the above example, cases 1 and 2 are not having with any statements.
Case 3 has two statements.
Similarly, for cases 4 and 5 also.
What is the logic behind such kind of programming practice?
The logic is if the value of x is 1 or 2 or 3, the statements in case 3 will get executed.
Similarly, if the value of x is 4 or 5, case 5 statements will get executed.