TeachingBee

Switch Case in C

Switch Case In C

Conditional Statements in C programming language is the fundamental concept that controls the flow of a program that is based on some certain conditions. These statements executes some set of statements to perform some actions depending on whether the condition is true or not. There are various types of Conditional statements in C. One of them is Switch case in C.

What Are Switch Case in C?

Switch-case in C programming provide an efficient way to handle multiple conditions.The switch statement evaluates its expression, then looks down through the case clauses until it finds a match. It then executes the associated block of code and breaks out of the switch unless a break statement is omitted to allow fall through to the next case. The optional default clause runs if no match is found.

It can be considered as an alternative for nested if-else statements.It works like a set of if/else statements but provides a cleaner and more efficient way to branch execution based on the state of a single variable or expression.These statements are useful when dealing with variables or expressions that needs to be compared against several constant values.

Switch Case Syntax in C

switch (expression) {
    case constant1:
        // Code to be executed if expression equals constant1
        break;

    case constant2:
        // Code to be executed if expression equals constant2
        break;

    // Additional cases can be added as needed

    default:
        // Code to be executed if expression doesn't match any case
}

Components of Switch statement in C

  • Switch statement: It takes the expression whose value is to be evaluated against the constant values in the case statements. It evaluates only int and char type data.
  • Case statements: If the expression matches with the constant value of any Case statements, the code block following that case will be executed.
  • Break statement: This statement is responsible to prevent the fall through behavior of Switch statements. If the Break statement is not added, then all the next case statements will be executed regardless whether the condition is met.
  • Default statement: This statement is executed when none of the case statements matches.

Flowchart of Switch Case Statement In C

Switch Case Statement

Best Practices of Switch Statement in C

  • Case statements in a switch statement should ideally be constants. Use of complex expressions may lead to unexpected behaviour.
  • Default statement should always be added to deal with invalid values.
  • Break statements should always be used to avoid the problem of Fall Through.
  • Nested Switch statements should not be used unnecessarily.

Break Statement in Switch Case Statements

In a switch statement in C, break statement is used to exit the block. It prevents the fall-through behaviour of switch statements. Fall-Through is a concept in which if a case meets the condition and is executed, the next case statements will also get executed as there was no break statement.

Example of Switch Statement in C without Break Statement

Let’s see example of switch statement without break statement

#include <stdio.h>

int main() {
    int num = 2;

    switch (num) {
        case 1:
            printf("This is case 1\n");
        
        case 2:
            printf("This is case 2\n");
        
        case 3:
            printf("This is case 3\n");
    }

    return 0;
}

Without break statements, switch statements exhibit “fall through” behaviour“, meaning execution continues on into the next case blocks regardless of whether that case matched the switch expression value.

So after printing “This is case 2“, execution falls through to case 3 which then prints out “This is case 3“.

Finally, the execution reaches the end of the switch and continues to the return statement. So the output will be:

Output

br

In this example, the control falls through the next case statement after the matched case is executed.

Example of Switch Statement with Break Statement

Let’s see example of switch statement with break statement

#include <stdio.h>

int main() {
    int num = 2;

    switch (num) {
        case 1:
            printf("This is case 1\n");
            break;
        
        case 2:
            printf("This is case 2\n");
            break;
        
        case 3:
            printf("This is case 3\n");
            break;
    }

    return 0;
}

Output

br1

In this example, the control does not falls through the next case statement after the matched case is executed break statement is used.

Default Statement in Switch Case Statements

Switch statement in C includes a Default statement that is executed when none of the case statements matches. Although its optional, but yet it is recommended to deal with invalid or unexpected values.

Example of Switch Statement with Default Statement

Let’s see example of switch statement with default statement

#include <stdio.h>

int main() {
    char grade = 'D’;

    switch (grade) {
        case 'A':
            printf("Excellent!\n");
            break;
        
        case 'B':
            printf("Good job!\n");
            break;
        
        case 'C':
            printf("Satisfactory.\n");
            break;
        
        default:
            printf("Invalid grade or not specified.\n");
    }

    return 0;
}

Output

df

In this example, the program evaluates the ‘grade’ variable. Since the value of ‘grade’ variable does not matches with any of the case statement’s condition, it is handled by the Default statement.

Switch Case Example in C

Write a program in C that takes a number representing a day of the week and prints whether it’s a weekday or weekend.

Algorithm

  1. Take input for the day of the week and store it in a variable ‘day’.
  2. Use switch-case statement and pass ‘day’ in it.
  3. Write case statements for values 1-5.
  4. Write case statements for 6-7.
  5. Use default statement for any other values.

Source Code

#include <stdio.h>

int main() {
    int day;

    printf("Enter a day (1-7): ");
    scanf("%d", &day);

    switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
            printf("Weekday\n");
            break;

        case 6:
        case 7:
            printf("Weekend\n");
            break;

        default:
            printf("Invalid day\n");
    }

    return 0;
}

Output

When day is equal to 1 or 2 or 3 or 4 or 5

s1

When day is equal to 6 or 7

s2

When holds any invalid or unexpected value

s3 3

Nested Switch-Case Statement in C

Nested switch-case statement in C involves using one or more switch-case statements inside another switch-case statement. This is a way to handle the scenarios where there are multiple levels of conditions.

Nested Switch-Case Statement Example in C

Write a program in C using nested switch-case that takes the details of food and based on given input, identify the food.

Algorithm

  1. Take ‘category’ and ‘itemCode’ as input.
  2. Use an outer switch-case statement and pass ‘category’ in it.
  3. Write case statements for ‘fruit’ and ‘vegetable’ category .
  4. If ‘category’ = 1, then it will display the category is ‘Fruits’. Inside this case statement, use an inner switch statement that will evaluate the ‘itemcode’ and will display the name of the fruit.
  5. And if ‘category’ = 2, then it will display the category is ‘Vegetables’. Inside this case statement, use an inner switch statement that will evaluate the ‘itemcode’ and will display the name of the vegetable.
  6. Use default statement to handle unknown categories.

Source Code

#include <stdio.h>

int main() {
    int category = 2;
    int itemCode = 103;

    switch (category) {
        case 1:
            printf("Category: Fruits\n");
            
            switch (itemCode) {
                case 101:
                    printf("Apple\n");
                    break;
                case 102:
                    printf("Banana\n");
                    break;
                case 103:
                    printf("Orange\n");
                    break;
                default:
                    printf("Unknown fruit\n");
            }
            break;

        case 2:
            printf("Category: Vegetables\n");

            switch (itemCode) {
                case 201:
                    printf("Carrot\n");
                    break;
                case 202:
                    printf("Spinach\n");
                    break;
                case 203:
                    printf("Tomato\n");
                    break;
                default:
                    printf("Unknown vegetable\n");
            }
            break;

        default:
            printf("Unknown category\n");
    }

    return 0;
}

Output

ns

Advantages of Switch-Case Statement

  1. Switch statement is an efficient choice for handling multiple conditions.
  2. Switch statement makes the code easier to read.
  3. Switch statement provides a more organised structure that helps in efficient decision making.

Disadvantages of Switch-Case Statement

  1. Switch statement does not support complex expressions.
  2. Switch statement has a drawback called fall-through and require break statements to prevent it.
  3. Switch statement cannot directly compare words or sentences.

Conclusion

In this article, we explored the switch statement in C programming and learned how to code and execute it. The switch statement is a type of conditional statement that is used to handle multiple conditions efficiently. And to its organised structure it has become a favoured choice by the programmers. Happy Learning!

Similar Posts

Goto Statements In C

Strong Number In C

I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

Can we use float or double data types in switch case expressions in C?

Is default case mandatory in a switch statement?

What are similarities and differences between IF-ELSE and SWITCH-CASE statements in C?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

Subtraction of Two Numbers Program in C

In this blog post, we will checkout the Subtraction of Two Numbers Program in C. How to Write Subtraction Program in C? To create a C program to subtract two

Add Two Numbers In C

In this blog post, we will checkout the how to add two numbers in C. Algorithm to Add Two Numbers in C To create a C program to add two

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In