Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Switch Statement in C

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Hello Ninja, welcome to the new article where we will learn about a switch case program in C. Understanding switch case programs in C can be of importance while executing a specific block of code based on the value of the expression.

Switch Case Program in C

So, why wait? Let's dive deep into the topic.

Switch Case Program 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 

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.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.

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.

Example

Code

  • c

c

#include <stdio.h>

int main() {
int choice;
printf("Enter a number: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("You chose option 1.\n");
break;
case 2:
printf("You chose option 2.\n");
break;
case 3:
printf("You chose option 3.\n");
break;
default:
printf("Invalid choice.\n");
break;
}

return 0;
}

Output

Also see, Floyd's Triangle in C

Rules for Switch Case Statement

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.

Code in C

Let's check how to use a switch in day to day coding. We will initialise a number ‘num’ as 3 and let's see how to execute some code when num is 3, using the switch. 

  • C

C

#include <stdio.h>

int main() {
   // Initialize a number
  int num = 3;
  
  // Switch statement
  switch(num) {
     // First case
     case 1:
        printf("The number is 1");
        break;
        
     // Second case
     case 2:
        printf("The number is 2");
        break;
        
     // Third case
     case 3:
        printf("The number is 3");
        break;
        
     // Default case
     default:
        printf("The number is not 1, 2 or 3");
        break;
  }
 
  return 0;
}

Output 

The number is 3


Explanation

In the above code, the switch statement initialises a number ‘num’ as 3. The expression does not match with any of case 1 and case 2. But the expression matches with case 3. Hence the statement in case 3 is executed.

Also read, Bit stuffing program in c

How does a switch Statement Work?

A switch statement is like picking from a menu of choices in a restaurant. You tell the waiter what you want, and they bring you the right dish. Similarly, in programming, you provide a bunch of options, and when the computer encounters a situation, it looks at those options and does the right thing. It's like having a set of instructions ready for different scenarios, so you don't have to explain everything every time. This makes your code shorter and easier to understand. It is like a smart decision-maker in programming. Imagine you have a set of options, and you want to do something different for each option. Instead of asking a bunch of questions, you give the computer a list of choices. When the computer encounters a situation, it looks at the list and picks the right action directly. It's like having a menu; you tell the computer what to do for each choice, and it chooses the correct one based on the situation. This makes it faster and more organised than asking questions one by one.

Think of a switch statement as a decision-maker in a game. You have a character, and depending on the situation, the character can do different things. Instead of asking a lot of "if" questions, you just say, "If the situation is like this, do this action." It's like having a menu of choices, and based on what's happening, you pick the right choice. This way, you can quickly decide what to do without asking a lot of questions every time.

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.

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

When using the switch statement in programming, the value you're checking (the one inside the parentheses after switch) needs to be something that doesn't change, like a fixed number. It's like when you're picking from a set menu – you can't change what's written on the menu itself. So, the value you put in the switch statement needs to be a constant, something that stays the same, like a number that doesn't vary.

Think of the "switch" statement in programming like a special menu at a restaurant. The choices on this menu have to be things that don't change, like specific meals that are always available. You can't pick something that might change every time you look at the menu. 

Similarly, when you use the "switch" statement, the thing you're checking (like a number or a name) has to be like those fixed menu items – it can't change while the program is running. It has to be a constant value that's already decided and won't be different each time you use it.

2. Expression value should be only of int or char type.

When you're using the "switch" statement in programming, the value you're checking (the one inside the parentheses after "switch") has to be either a number or a single character. It's like when you're playing a game, and you need to use a key or a number to unlock a special door – the game only understands those types of things. So, when you use the "switch" statement, the value you're checking must be either a whole number (like 1, 2, 3) or a single letter/character (like 'a', 'b', 'c'). The computer needs to know exactly what you mean, and these types of values make it clear.

3. Case Values must be Unique

When you're using the "switch" statement in programming, you're checking different cases, like options on a menu. Just like on a menu, each option needs to be unique – you can't have the same dish listed twice. Similarly, when you're using "switch," each "case" value you write must be different from the others. They have to be unique, so the program can clearly tell which option you're talking about. It's like making sure every item on the menu has its own distinct name.

4. Nesting of switch Statements

"Nesting of switch statements" means putting one "switch" statement inside another, like placing a smaller box inside a larger one. This can be done in programming when you need to make more complex decisions.

Imagine you have a big menu at a fancy restaurant. Each section of the menu has its own options. You might choose a main course from one section and a dessert from another. In programming, you can use nested "switch" statements to handle choices like this.

Here's how it works: Inside the code for one "case" of the outer "switch," you can have another "switch" statement that checks for choices within that specific case.

It's like having a menu within a menu, where you make choices step by step. Just remember that too much nesting can make the code hard to understand, like a big stack of menus!

In short, nesting "switch" statements means using one "switch" inside another to handle more detailed choices, just like choosing dishes from different sections of a menu.

Examples of switch Statement in C

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

Implementation

  • 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;
}

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

Implementation

  • 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;
}

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.

Frequently Asked Questions

What is the purpose of the break statement in a switch case program in C?

The break statement is used to exit the switch case statement.

Can a switch case statement test for a range of values?

No, a switch case statement cannot test for a range of values. 

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

The default statement is executed when none of the cases matches.

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.

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

Yes, a switch case statement can be nested within another switch statement.

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:


To learn more about DSA, competitive coding, and many more knowledgeable topics, please look into the guided paths on Coding Ninjas Studio. Also, you can enroll in our courses and check out the mock test and problems available to you. Please check out our interview experiences for placement preparations.

Happy Coding!

Topics covered
1.
Introduction
2.
Switch Case Program in C
2.1.
Syntax 
3.
Default and Break Statements
3.1.
Break Statement 
3.2.
Default Case Statement
4.
How to use switch case Statement in C?
4.1.
Example
4.1.1.
Code
4.2.
c
4.2.1.
Output
5.
Rules for Switch Case Statement
6.
Code in C
6.1.
C
6.2.
Output 
7.
How does a switch Statement Work?
8.
Flowchart of Switch Statement
9.
Important Points About Switch Case Statements
9.1.
1. Switch expression should result in a constant value
9.2.
2. Expression value should be only of int or char type.
9.3.
3. Case Values must be Unique
9.4.
4. Nesting of switch Statements
10.
Examples of switch Statement in C
10.1.
Example 1: C Program to print the day of the week using a switch case.
10.1.1.
Implementation
10.2.
c
10.2.1.
Output
10.2.2.
Explanation
10.3.
Example 2: Simple Calculator using switch case in C
10.3.1.
Implementation
10.4.
c
10.4.1.
Output
10.4.2.
Explanation
11.
Advantages of Switch Case Program in C
12.
Disadvantages of Switch Case Program in C
13.
Why do we need a Switch case?
14.
Frequently Asked Questions
14.1.
What is the purpose of the break statement in a switch case program in C?
14.2.
Can a switch case statement test for a range of values?
14.3.
What is the purpose of the default statement in a switch case statement?
14.4.
Can we use functions in switch case in C?
14.5.
Can a switch case statement be nested inside another switch case statement?
15.
Conclusion