Table of contents
1.
Introduction
2.
What is Switch Statement in C?
3.
Syntax of Switch Statement in C
4.
How to use switch case Statement in C?
5.
Rules for Switch Statement in C
6.
How does a Switch Statement Work?
7.
Flowchart of Switch Statement
8.
Default and Break Statements
8.1.
Break Statement 
8.2.
Default Case Statement
9.
Examples of switch Statement in C
9.1.
Example 1: C Program to print the day of the week using a switch case.
9.2.
c
9.3.
Example 2: Simple Calculator using switch case in C
9.4.
c
10.
Advantages of Switch Case Program in C
11.
Disadvantages of Switch Case Program in C
12.
Why do we need a Switch case?
13.
Important Points About Switch Case Statements
14.
Frequently Asked Questions
14.1.
Can we use functions in switch case in C?
14.2.
Is default necessary in switch case in C?
14.3.
What is the purpose of the default statement in a switch case statement?
14.4.
Can a switch case statement be nested inside another switch case statement?
15.
Conclusion
Last Updated: Oct 9, 2024
Easy

Switch Statement in C

Author Rishabh
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The switch statement in C is a powerful control structure used to handle multiple conditions by directing program flow to different code blocks based on the value of a variable or expression. Unlike lengthy if-else chains, the switch statement offers a cleaner, more efficient way to manage decision-making processes in your programs. This blog will explore the syntax, usage, and best practices for using the switch statement in C.

Switch Case Program in C

What is Switch Statement in C?

A switch case program in C is a control statement that allows us to select one of the many possible paths of execution based on the value of an expression. The switch case program in C is an alternative to the if-else statement, which allows us to execute multiple operations for different values of the variable called as switch variable. 

Syntax of Switch Statement in C

switch(expression) {
  case a:
  	// Code block
  	break;
  	
  case b:
  	// Code block
  	break;
  	
  default:
  	// Code block
}


where,

The switch expression is evaluated once. If the expression matches with any case, the code block for that case executes, and the break statement breaks out of the loop. If none of the cases match, then the default code block is executed.

Note: The Switch Case program in C can only evaluate the integer or character value.

How to use switch case Statement in C?

In C programming, the switch case statement is used to make decisions based on different possible values of a variable. It's like a menu with different choices, and you choose what to do based on what you order.

Here's how you use it:

1. You start with the switch keyword and then put the variable you want to check in parentheses. This is the variable you want to make decisions about.

2. Inside the curly braces {}, you list different case options. Each case is like a different choice you're checking for.

3. After each case, you put a colon : and then write the code you want to run if the variable matches that particular choice.

4. You finish the case with the break keyword. This tells the program to stop checking and move on to the next part of the code after the switch statement.

5. You can also include a default case. This is like the "just in case" option. If none of the case values matches the variable, the code inside the default case will run.

Also see, Floyd's Triangle in C

Rules for Switch Statement in C

There are some rules we need to keep in mind while using switch case statement

  • The case value in the switch case statement must be of ‘char’ and ‘int’ type.
     
  • There can be any number of cases.
     
  • The values in the case must be unique.
     
  • The break statement and default case are optional but should be added for better readability.

Also read, Bit stuffing program in c

How does a Switch Statement Work?

1. Evaluate the Expression:

  • The expression inside the switch statement is evaluated.

2. Match Against Case Labels:

  • The value of the expression is compared with the values of each case label within the switch block.

3. Execute Matching Case:

  • If a match is found, the code associated with that case label is executed.

4. Break Statement:

  • After executing the matched case block, the break statement is encountered, which exits the switch statement. If break is not used, the execution continues to the next case block (known as "fall-through").

5. Default Case:

  • If no match is found, the default block (if provided) is executed. This serves as a fallback.

6. End of Switch Statement:

  • The switch statement ends after executing the matched case or default block, or after a break statement is encountered.

Flowchart of Switch Statement

Let's discuss the Flowchart of the Switch Statement.

Flowchart of Switch Statement

Start: The flowchart starts with an oval shape labeled "Start."

Input: A rectangle represents the user input section where the program asks the user for a value, like a number or a character.

Switch Decision: A diamond shape labeled "Switch" follows the input. Lines come out of the diamond, each leading to a rectangle labeled with a possible case value.

Cases: For each case, there's a rectangle where the specific action related to that case is performed, like a calculation or a message display.

Default Case: If there's a default case, there's another rectangle labeled "Default" where the program handles cases that don't match any of the specified cases.

End: An oval labeled "End" signifies the end of the flowchart.

Lines connect the shapes to show the flow of the program from input to various cases and then to the end. Each shape has arrows connecting it to the next appropriate shape.

So, flowcharts are visual tools, so if you need a detailed visual representation, you might want to use a flowchart drawing tool or software.

Default and Break Statements

Now we will look at the default and break statements which are used in switch case program in C

Break Statement 

The ‘break’ statement is used within each case to terminate the block and exit the switch case statement. Without the break statement, the code will continue to execute the following case blocks as well until it reaches another break statement.

Default Case Statement

The default Statement is used if none of the previous cases matches. The default case is optional and if none of the cases matches and there is no default case then the switch case simply terminates.

Examples of switch Statement in C

Example 1: C Program to print the day of the week using a switch case.

  • c

c

#include <stdio.h>

int main() {
int dayNumber;

// Ask the user to input a number (1 to 7) representing a day of the week
printf("Enter a number (1 to 7) to get the day of the week: ");
scanf("%d", &dayNumber);

switch (dayNumber) {
case 1:
printf("It's Sunday!\n");
break;
case 2:
printf("It's Monday!\n");
break;
case 3:
printf("It's Tuesday!\n");
break;
case 4:
printf("It's Wednesday!\n");
break;
case 5:
printf("It's Thursday!\n");
break;
case 6:
printf("It's Friday!\n");
break;
case 7:
printf("It's Saturday!\n");
break;
default:
printf("Invalid input! Please enter a number between 1 and 7.\n");
break;
}

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

print the day of the week

Explanation

Let's break it down step by step:

#include <stdio.h>: This line includes the standard input-output library, which allows you to use functions like printf and scanf.

int main(): This is the starting point of the program. The main function is where the program's execution begins.

int dayNumber;: This declares an integer variable named dayNumber to store the user's input.

printf("Enter a number (1 to 7) to get the day of the week: ");: This line displays a message prompting the user to enter a number between 1 and 7.

scanf("%d", &dayNumber);: This line reads the user's input and stores it in the dayNumber variable.

switch (dayNumber) { ... }: This is the switch case statement. It checks the value of dayNumber against different cases (numbers 1 to 7) and performs different actions based on the value.

case 1: printf("It's Sunday!\n"); break;: If dayNumber is 1, this line prints "It's Sunday!" and then break is used to exit the switch case.

Similar cases follow for days 2 to 7, each printing the corresponding day of the week.

default: printf("Invalid input! Please enter a number between 1 and 7.\n"); break;: If dayNumber doesn't match any of the cases, this default case is executed. It prints an error message and also includes a break.

return 0;: This line indicates that the program has finished executing and is returning the value 0 to the operating system. A value of 0 typically means successful execution.

Example 2: Simple Calculator using switch case in C

  • c

c

#include <stdio.h>

int main() {
int num1, num2, result;
char operator;

// Ask the user for input
printf("Enter first number: ");
scanf("%d", &num1);

printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Note the space before %c to consume any leftover newline character

printf("Enter second number: ");
scanf("%d", &num2);

switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %d\n", result);
break;
case '-':
result = num1 - num2;
printf("Result: %d\n", result);
break;
case '*':
result = num1 * num2;
printf("Result: %d\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("Result: %d\n", result);
} else {
printf("Error: Division by zero is not allowed.\n");
}
break;
default:
printf("Error: Invalid operator.\n");
break;
}

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Simple Calculator

Explanation

Here's a breakdown of how it works:

#include <stdio.h>: This line includes the standard input-output library, which provides functions like printf and scanf.

int main(): This is the starting point of the program. The main function is where the execution begins.

Declare variables: int num1, int num2, int result, and char operator are declared to store the two numbers, the result of the calculation, and the chosen operator, respectively.

User input: The program prompts the user to enter the first number using printf and receives the input using scanf.

Operator input: The program then asks the user to enter an operator (+, -, *, /) to indicate the desired operation. The space before %c in scanf(" %c", &operator); is used to consume any leftover newline character from the previous input.

Second number input: Similarly, the program prompts for and receives the second number from the user.

Switch case: The program uses a switch statement to determine the operation based on the entered operator.

For each operation (+, -, *, /), there's a corresponding case. Inside each case, the appropriate calculation is performed and stored in the result variable. Then, using printf, the result is displayed.

If the operator is /, the program checks if num2 is not zero before performing division. If num2 is zero, it displays an error message to avoid division by zero.

If none of the specified operators match the entered one, the default case is executed, showing an error message for an invalid operator.

return 0;: This line indicates that the program has finished executing and is returning the value 0 to the operating system. A return value of 0 typically signifies successful execution.

Advantages of Switch Case Program in C

  • A switch case statement can make the code easier to understand, especially when there are multiple conditions to evaluate.
     
  • A switch case statement can be more efficient than multiple if-else statements.
     
  • Switch case programs in C can be easier to modify as adding any statement is easy.

Disadvantages of Switch Case Program in C

  • Switch case statements only work for integers and characters, making it limited to use other expression types.
     
  • We need to be careful while using break statements, as improper use of break statements can cause unexpected behavior.

Why do we need a Switch case?

The switch statement in C programming language serves several important purposes:

  • Enhanced Readability: The switch statement enhances code readability by providing a concise and structured way to handle multiple conditions. It's particularly useful when dealing with a large number of possible values for a variable.
  • Simplified Syntax for Multiple Conditions: It offers a more readable and simplified syntax compared to using a series of nested if-else statements. This is especially beneficial when a variable is tested against multiple values, reducing the indentation level and making the code more maintainable.
  • Efficient Execution: In some cases, a switch statement can be more efficient than a series of equivalent if-else statements. Compilers can optimize the code generated for a switch statement, leading to potentially faster execution.
  • Logical Structure: The switch statement provides a logical structure for handling multiple cases, making the code easier to understand and maintain. It helps avoid the complexity of deeply nested if-else structures.
  • Fall-Through Capability: The switch statement supports fall-through behavior, where execution continues from one case to the next without a break statement. This can be useful in specific scenarios, allowing multiple cases to share the same code.
  • Code Consistency: The use of a switch statement contributes to code consistency. When a variable is tested against multiple values, having a standardized structure helps maintain consistency across the codebase, making it easier for developers to understand and contribute.
  • Default Case Handling: The switch statement allows for a default case, which is executed when none of the specified cases matches the variable's value. This helps ensure that there is a predefined action for unexpected or unhandled values.

Important Points About Switch Case Statements

Let's discuss a few important points about switch case statements.

  1. Switch expression should result in a constant value
  2. Expression value should be only of int or char type.
  3. Case Values must be Unique
  4. Nesting of switch Statements

Frequently Asked Questions

Can we use functions in switch case in C?

No, C does not allow functions directly in switch cases. switch cases are designed for constant expressions, not functions. Use if-else statements if functionality based on function results is needed.

Is default necessary in switch case in C?

The default case in a switch statement is not necessary, but it is recommended. It acts as a fallback for unmatched cases, ensuring that some code runs even if no case matches.

What is the purpose of the default statement in a switch case statement?

The default statement provides a block of code that executes when none of the case labels match the switch expression. It ensures a response for all possible values.

Can a switch case statement be nested inside another switch case statement?

Yes, a switch case statement can be nested inside another switch case statement in C. This allows complex conditional logic within each case block.

Conclusion

In this article, we discussed the Switch Case Program in C. You can also read the article Differences between if else and switch to improve your knowledge about List and Set.

To learn more, check out our articles:

Live masterclass