Back to: C Tutorials For Beginners and Professionals
Switch Statements in C Language with Examples
In this article, I will discuss the Switch Statements in C Language with Examples. Please read our previous articles discussing Nested If Else Statements in C Language with Examples. At the end of this article, you will understand what switch statement is in C and when and how to use switch statements in C Programming Language.
Switch Statements in C Language:
Switch statements in the C language are a form of control structure that allows for more efficient and readable handling of multiple conditional branches. They are useful when you have a variable that can take one of many possible values and want to execute different code depending on its value.
The switch is a keyword. By using the switch keyword, we can create selection statements with multiple blocks. Multiple blocks can be constructed by using a “case” keyword.
Switch case statements are a substitute for long if statements that compare a variable to several integral values. The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. The switch is a control statement that allows a value to change execution control.
Rules for Switch statements in C Language:
- The expression provided in the switch should result in a constant value. Otherwise, it would not be valid.
- Duplicate case values are not allowed.
- The default statement is optional. Even if the switch case statement has no default statement, it will run without problem.
- The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the control flow jumps to the next line following the switch statement.
- The break statement is optional. If omitted, execution will continue into the next case. The control flow will fall through to subsequent cases until a break is reached.
- Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However, nested switch statements should be avoided as they make the program more complex and less readable.
Syntax of Switch Statements in C Language:
switch(expression) { case value1: // Code to execute when expression equals value1 break; case value2: // Code to execute when expression equals value2 break; ... default: // Code to execute if expression doesn't match any case }
Here,
- expression: This is evaluated once at the beginning of the switch statement. Its result is compared with the values in each case.
- case valueN: If the expression matches valueN, the code following this case will execute.
- break: It’s used to exit the switch block. Without a break, the execution continues into the next case.
- default: This block is executed if none of the case values match the expression. It’s optional.
After the end of each block, it is necessary to insert a break statement because if the programmers do not use the break statement, all consecutive blocks of codes will get executed from every case onwards after matching the case block.
When do we need to go for a switch statement?
When there are several options, and we have to choose only one option from the available options depending on a single condition, then we need to go for a switch statement. Depending on the selected option, a particular task can be performed.
Example to understand Switch Statement in C Language:
#include <stdio.h> int main() { int x = 2; switch (x) { case 1: printf("Choice is 1"); break; case 2: printf("Choice is 2"); break; case 3: printf("Choice is 3"); break; default: printf("Choice other than 1, 2 and 3"); break; } return 0; }
Output: Choice is 2
Example Program
Let’s consider an example where you want to display the name of a day based on its numeric representation (1 for Monday, 2 for Tuesday, etc.).
#include <stdio.h> int main() { int day; printf("Enter day number (1-7): "); scanf("%d", &day); switch(day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; case 4: printf("Thursday\n"); break; case 5: printf("Friday\n"); break; case 6: printf("Saturday\n"); break; case 7: printf("Sunday\n"); break; default: printf("Invalid day number. Enter a number between 1 and 7.\n"); } return 0; }
In this example, the switch statement checks the value of the day. If it matches any of the case values (from 1 to 7), it prints the corresponding day of the week. If the day doesn’t match any of these values, the default case is executed.
Example: Menu Selection
#include <stdio.h> int main() { int choice; printf("Select an option:\n1. Play\n2. Load\n3. Settings\n4. Exit\n"); scanf("%d", &choice); switch (choice) { case 1: printf("Starting game...\n"); break; case 2: printf("Loading game...\n"); break; case 3: printf("Opening settings...\n"); break; case 4: printf("Exiting...\n"); break; default: printf("Invalid choice\n"); } return 0; }
Example: Grade Evaluation
#include <stdio.h> int main() { char grade; printf("Enter your grade (A-D): "); scanf(" %c", &grade); // Note the space before %c to catch any whitespace switch (grade) { case 'A': case 'a': printf("Excellent\n"); break; case 'B': case 'b': printf("Good\n"); break; case 'C': case 'c': printf("Average\n"); break; case 'D': case 'd': printf("Poor\n"); break; default: printf("Invalid grade\n"); } return 0; }
What is the Difference Between Nested If-Else and Switch Statements in C Language?
By using nested if-else, we can also create multiple blocks whenever required, but to create “n” no of blocks, we are required to create “n-1” conditions. In the switch statement, we can create multiple blocks under a single condition that reduces the coding part.
When we are working with nested if-else at any point in time among all those blocks, only one block gets executed. But in the switch statement, we can create more than one block depending on the requirement by removing the break statement between the blocks.
Question 1: What will be the output in the Program Below?
#include <stdio.h> int main() { int i; i = 3; switch(i) { case 1: printf("A"); break; case 3: printf("C"); case 2: printf("B"); break; default: printf("D"); } return 0; }
Output: CB
This is because whenever we work with switch statements randomly, we can create the cases i.e., in any sequence it can be created. In order to execute the switch block, it can execute all cases in sequence from the matching case onwards until it finds the break statement.
Question 2: What will be the output in the Program Below?
#include <stdio.h> int main() { int i; i = 5; switch(i) { case 1: printf("A"); break; default: printf("D"); case 2: printf("B"); break; case 3: printf("B"); } }
Output: DB
This is because when working with the default, it can be placed anywhere within the switch body, i.e., the top of the switch statement, the middle of the switch statement, or the end of the switch statement. But, it is recommended to place it at the end of the switch body. Placing the default is always optional. It is required to be placed whenever we are not handling all statements of the switch body.
Question 3: What will be the output in the Program Below?
#include <stdio.h> int main() { float i; i = 2; //i = 2.0 switch(i) { case 1: printf("A"); break; case 2: printf("B"); break; case 3: printf("C"); break; default: printf("D"); } return 0; }
Output:
This is because whenever we are working with the switch statement, it requires condition and expression of type integer only, i.e., float data we cannot pass within the switch.
Question 4: What will be the output in the Program Below?
#include <stdio.h> int main() { int i; i = 2; switch(i) { case 1.0: printf("A"); break; case 2.0: printf("B"); break; case 3.0: printf("C"); break; default: printf("D"); } return 0; }
Output:
This is because the case keyword requires a condition or expression of integer type value only, i.e., we cannot pass float data as a case constant value.
Question 5: What will be the output in the Program Below?
#include <stdio.h> int main() { int a = 1, b = 2, c = 3; int d = c-a; switch(d) { case a: printf("A1"); break; case b: printf("B2"); break; case c: printf("C3"); break; default: printf("D4"); } return 0; }
Output:
Question 6: What will be the output in the Program Below?
#include <stdio.h> int main() { int i; i = 3-2; switch(i) { case 2%2: printf("A"); break; case 5/2: printf("B"); break; case 3*2-3-2: printf("C"); break; default: printf("D"); } return 0; }
Output: C
This is because when we are passing expression format data, it works according to the return type of the expression.
Question 7: What will be the output in the Program Below?
#include <stdio.h> int main() { int i; i = 5 < 8; switch(i) { case 2>5: printf("A"); break; case !2 != 2: printf("B"); break; case 8 < 5: printf("C"); break; default: printf("D"); } return 0; }
Output:
This is because, in switch statements, we cannot create more than one case with the same constant value. If we create, the compiler will give an error called duplicate case.
Points Remember while working with Switch Statement in C Language:
- When working with the switch statement during compilation, the switch condition/expression return value will match the case constant value. At the time of execution, if the matching case occurs, then control will pass to the correspondent block. From the matching case up to the break, everything will be executed. If the break does not occur, all cases will be executed, including default.
- At the time of execution, if the matching case does not occur, then control will pass to the default block. Default is a special kind of case that will be executed automatically when the matching case does not occur. Using default is always optional, but it is recommended when we are not handling all cases of the switch block.
In the next article, I will discuss While Loop in C Language with Examples. Here, in this article, I try to explain Switch Statements in C Language with Examples. I hope you enjoy this article on Switch Statements in C Language with Examples. I would like to have your feedback. Please post your feedback, questions, or comments about this article.