Professional Documents
Culture Documents
Week 2
Week 2
Switch Statement
Switch statement in C tests the value of a variable and compares it with multiple cases. Once
the case match is found, a block of statements associated with that particular case is executed.
Each case in a block of a switch has a different name/number which is referred to as an
identifier. The value provided by the user is compared with all the cases inside the switch block
until the match is found. If a case match is NOT found, then the default statement is executed,
and the control goes out of the switch block.
Switch Flowchart
Switch Syntax
Rules for Switch Statement
The following are rules for switch statement in C:
1. An expression must always execute to a result.
2. Case labels must be constants and unique.
3. Case labels must end with a colon ( : ).
4. A break keyword must be present in each case.
5. There can be only one default label.
6. We can nest multiple switch statements.
Sample Problem 1
Sample Outputs:
Sample Problem 2:
Sample Outputs:
Problem Set 1:
Write a C program to print day of week name using switch statement.
Sample Outputs:
Note: If you encounter an infinite loop during runtime, press Ctr C to stop the infinite loop.
Problem Set 2:
Write a C program to check whether the number is even or odd using switch statement.
Sample Output:
Note: You may use Dev C++ IDE or you may use www.codechum.com ‘s playground for your coding.