How to Use Switch Case in C Language
In C programming, the switch case statement is a powerful tool that allows you to execute different blocks of code based on the value of a given expression. This is particularly useful when you want to perform different actions depending on the input or the value of a variable. In this article, we will explore how to use the switch case in C language, including its syntax, usage, and some practical examples.
The switch case statement works by evaluating an expression and then comparing its value with a series of case labels. When a match is found, the corresponding block of code is executed. If no match is found, a default block of code can be executed. Let’s dive into the syntax and usage of the switch case statement in C.
The syntax of the switch case statement is as follows:
“`c
switch (expression) {
case constant1:
// code block 1
break;
case constant2:
// code block 2
break;
…
default:
// code block for default case
}
“`
Here’s a breakdown of the syntax:
– `switch (expression)`: This is the switch case statement’s header. The `expression` is evaluated, and its value is compared with the case labels.
– `case constant`: This is a label that represents a constant value. When the expression matches this value, the corresponding code block is executed.
– `break`: This statement is used to exit the switch case statement. Without it, the code will fall through to the next case, which can lead to unexpected behavior.
– `default`: This is an optional block of code that is executed if none of the case labels match the expression. It is similar to an else statement in an if-else structure.
Now, let’s look at some practical examples to illustrate how the switch case statement can be used in C.
Example 1: Calculate the day of the week based on an integer input.
“`c
include
int main() {
int day;
printf(“Enter a number (1-7) to get the day of the week: “);
scanf(“%d”, &day);
switch (day) {
case 1:
printf(“Monday”);
break;
case 2:
printf(“Tuesday”);
break;
case 3:
printf(“Wednesday”);
break;
case 4:
printf(“Thursday”);
break;
case 5:
printf(“Friday”);
break;
case 6:
printf(“Saturday”);
break;
case 7:
printf(“Sunday”);
break;
default:
printf(“Invalid input!”);
}
return 0;
}
“`
Example 2: Check if a given number is even or odd.
“`c
include
int main() {
int num;
printf(“Enter an integer: “);
scanf(“%d”, &num);
switch (num % 2) {
case 0:
printf(“%d is even.”, num);
break;
case 1:
printf(“%d is odd.”, num);
break;
default:
printf(“Invalid input!”);
}
return 0;
}
“`
In conclusion, the switch case statement is a versatile tool in C programming that can help you write more efficient and readable code. By following the syntax and understanding the usage of the switch case statement, you can easily implement conditional logic based on the value of an expression.