Introduction
In the previous chapter, we learned about the if-else statement in C. In this chapter, we will focus on the switch statement. The switch statement is a control flow structure that allows you to execute one of many code blocks based on the value of a variable or expression. It provides an alternative to using multiple if-else statements and can make your code more readable and easier to manage.
What is a switch Statement?
The switch statement tests the value of a variable or expression against multiple cases and executes the corresponding block of code for the matching case. If no case matches, an optional default case can be used to execute a block of code when none of the specified cases match.
How the switch Statement Works
- Evaluate the Expression: The value of the expression inside the
switchstatement is evaluated. - Compare with Cases: The evaluated value is compared with the values of each
caselabel. - Execute Matching Case: If a match is found, the corresponding block of code is executed.
- Break Statement: The
breakstatement is used to exit theswitchstatement. If omitted, the execution will continue to the next case. - Default Case: If no match is found, the
defaultcase (if present) is executed.
Syntax
The basic syntax of a switch statement in C is as follows:
switch (expression) {
case constant1:
// Code to execute if expression equals constant1
break;
case constant2:
// Code to execute if expression equals constant2
break;
// You can have any number of case statements
default:
// Code to execute if expression doesn't match any case
}
expression: This is the variable or expression whose value is being compared.case constant: Eachcasekeyword is followed by a constant value and a colon. The code block following acaseis executed if the expression matches the constant.break: Thebreakstatement terminates theswitchcase. If omitted, the program continues to the next case.default: Thedefaultcase is optional and executes if no other case matches. It is similar to theelsestatement in anif-elseladder.
Simple Example
Let’s look at a simple example to understand how the switch statement works.
Example: Day of the Week
#include <stdio.h>
int main() {
int day = 3; // Declaring an integer variable 'day' and assigning it a value of 3
switch (day) {
case 1:
printf("Monday\n"); // Printing if 'day' is 1
break;
case 2:
printf("Tuesday\n"); // Printing if 'day' is 2
break;
case 3:
printf("Wednesday\n"); // Printing if 'day' is 3
break;
case 4:
printf("Thursday\n"); // Printing if 'day' is 4
break;
case 5:
printf("Friday\n"); // Printing if 'day' is 5
break;
case 6:
printf("Saturday\n"); // Printing if 'day' is 6
break;
case 7:
printf("Sunday\n"); // Printing if 'day' is 7
break;
default:
printf("Invalid day\n"); // Printing if 'day' does not match any case
break;
}
return 0; // Returning 0 to indicate successful execution
}
Output:
Wednesday
Using break
The break statement is crucial in a switch statement. It terminates the switch case and prevents the execution from falling through to subsequent cases. If the break statement is omitted, the program will continue to execute the next case even if it does not match the expression.
Example: Omitting break Statement
#include <stdio.h>
int main() {
int day = 3; // Declaring an integer variable 'day' and assigning it a value of 3
switch (day) {
case 1:
printf("Monday\n"); // Printing if 'day' is 1
case 2:
printf("Tuesday\n"); // Printing if 'day' is 2
case 3:
printf("Wednesday\n"); // Printing if 'day' is 3
case 4:
printf("Thursday\n"); // Printing if 'day' is 4
case 5:
printf("Friday\n"); // Printing if 'day' is 5
case 6:
printf("Saturday\n"); // Printing if 'day' is 6
case 7:
printf("Sunday\n"); // Printing if 'day' is 7
default:
printf("Invalid day\n"); // Printing if 'day' does not match any case
}
return 0; // Returning 0 to indicate successful execution
}
Output:
Wednesday
Thursday
Friday
Saturday
Sunday
Invalid day
In this example, because there are no break statements, the program continues to execute all subsequent cases after the matching case.
Different Use Cases of switch Statement
1. Menu Selection
The switch statement is often used to create a menu selection system.
#include <stdio.h>
int main() {
int choice;
printf("Menu:\n");
printf("1. Start\n");
printf("2. Stop\n");
printf("3. Pause\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Starting...\n");
break;
case 2:
printf("Stopping...\n");
break;
case 3:
printf("Pausing...\n");
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice.\n");
break;
}
return 0; // Returning 0 to indicate successful execution
}
2. Grade Calculation
Using the switch statement to determine the grade based on marks.
#include <stdio.h>
int main() {
int marks;
printf("Enter your marks: ");
scanf("%d", &marks);
switch (marks / 10) {
case 10:
case 9:
printf("Grade: A\n");
break;
case 8:
printf("Grade: B\n");
break;
case 7:
printf("Grade: C\n");
break;
case 6:
printf("Grade: D\n");
break;
default:
printf("Grade: F\n");
break;
}
return 0; // Returning 0 to indicate successful execution
}
3. Character Evaluation
Using the switch statement to categorize characters.
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
printf("Vowel\n");
break;
default:
printf("Consonant\n");
break;
}
return 0; // Returning 0 to indicate successful execution
}
4. Math Operations
Using the switch statement to perform different math operations.
#include <stdio.h>
int main() {
char operator;
double num1, num2;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Notice the space before %c to consume any leftover whitespace
printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);
break;
case '-':
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);
break;
case '/':
if (num2 != 0.0)
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);
else
printf("Error! Division by zero.\n");
break;
default:
printf("Invalid operator.\n");
break;
}
return 0; // Returning 0 to indicate successful execution
}
Conclusion
The switch statement is used for handling multiple conditions in your C programs. It provides a clear and efficient way to execute different blocks of code based on the value of a variable or expression. By understanding and using the switch statement, case labels, break statements, and the default case, you can write more readable and maintainable code.