C Programming Language Tutorial

Variables and Data Types

Input/Output

Looping and Selection Structures

Array

Functions

Preprocessing Command

Pointer

Structure

File Operations

Important Knowledge

switch case Statements in C Programming Language

In this tutorial, we'll explore the concept of the switch statement with case labels in the C programming language. We'll cover the basic syntax and provide examples to demonstrate its usage.

Switch Case Statement

The switch statement is a control flow statement that allows you to perform different actions based on the value of a single variable or expression. It provides an alternative to using a series of if-else statements when you need to choose from several options based on a single value.

Syntax

To use the switch statement, you can use the following syntax:

switch (expression) {
    case constant1:
        // code block to execute if expression equals constant1
        break;

    case constant2:
        // code block to execute if expression equals constant2
        break;

    // more cases

    default:
        // code block to execute if none of the constants match the expression
}
  • expression: The variable or expression you want to compare against the case constants.
  • constant1, constant2, etc.: The constant values that the expression can take.
  • break: A statement that causes the program to exit the current switch statement and resume execution after it.
  • default: An optional block of code that will execute if none of the case constants match the expression.

Examples

Here are some examples demonstrating the use of the switch statement with case labels in C:

  • Basic usage of the switch statement:
#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        case 5:
            printf("Friday\n");
            break;
        case 6:
            printf("Saturday\n");
            break;
        case 7:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

In this example, we use the switch statement to print the name of the day based on the day variable. The program will output "Wednesday" as day is set to 3.

  • Using the switch statement with an enumeration:
#include <stdio.h>

enum Weekday {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};

void print_day(enum Weekday day);

int main() {
    enum Weekday day = WEDNESDAY;
    print_day(day);

    return 0;
}

void print_day(enum Weekday day) {
    switch (day) {
        case MONDAY:
            printf("Monday\n");
            break;
        case TUESDAY:
            printf("Tuesday\n");
            break;
        case WEDNESDAY:
            printf("Wednesday\n");
            break;
        case THURSDAY:
            printf("Thursday\n");
            break;
        case FRIDAY:
            printf("Friday\n");
            break;
        case SATURDAY:
            printf("Saturday\n");
            break;
        case SUNDAY:
            printf("Sunday\n");
            break;
        default:
            printf("Invalid day\n");
    }
}

In this example, we use an enumeration to represent the days of the week and a switch statement in the print_day() function to print the name of the day based on the enumeration.

  1. Handling multiple conditions with switch-case in C language:

    • Description: The switch-case statement provides an efficient way to handle multiple conditions based on the value of an expression.
    • Example:
      #include <stdio.h>
      
      // Handling multiple conditions with switch-case in C
      int main() {
          int day = 3;
      
          switch (day) {
              case 1:
                  printf("Monday\n");
                  break;
              case 2:
                  printf("Tuesday\n");
                  break;
              case 3:
                  printf("Wednesday\n");
                  break;
              default:
                  printf("Unknown day\n");
          }
      
          return 0;
      }
      
  2. Switch-case vs. if-else statements in C programming:

    • Description: Both switch-case and if-else statements can be used for conditional branching, but switch-case is often preferred when dealing with multiple values for a single variable.
    • Example:
      #include <stdio.h>
      
      // Switch-case vs. if-else statements in C programming
      int main() {
          char grade = 'B';
      
          switch (grade) {
              case 'A':
                  printf("Excellent\n");
                  break;
              case 'B':
                  printf("Good\n");
                  break;
              case 'C':
                  printf("Average\n");
                  break;
              default:
                  printf("Fail\n");
          }
      
          // Equivalent if-else statements
          /*
          if (grade == 'A') {
              printf("Excellent\n");
          } else if (grade == 'B') {
              printf("Good\n");
          } else if (grade == 'C') {
              printf("Average\n");
          } else {
              printf("Fail\n");
          }
          */
      
          return 0;
      }
      
  3. Using break and fall-through in switch-case constructs:

    • Description: The break statement is used to exit the switch-case block. Fall-through occurs when multiple cases share the same code.
    • Example:
      #include <stdio.h>
      
      // Using break and fall-through in switch-case constructs
      int main() {
          int choice = 2;
      
          switch (choice) {
              case 1:
                  printf("Option 1 selected\n");
                  break;
              case 2:
              case 3:
                  printf("Option 2 or 3 selected\n");  // Fall-through
                  break;
              default:
                  printf("Invalid option\n");
          }
      
          return 0;
      }
      
  4. Switch-case with enums and constants in C:

    • Description: Enums and constants can be used in switch-case for better readability and maintainability.
    • Example:
      #include <stdio.h>
      
      // Switch-case with enums and constants in C
      enum Days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY };
      
      int main() {
          enum Days today = WEDNESDAY;
      
          switch (today) {
              case MONDAY:
                  printf("It's Monday\n");
                  break;
              case TUESDAY:
                  printf("It's Tuesday\n");
                  break;
              case WEDNESDAY:
                  printf("It's Wednesday\n");
                  break;
              default:
                  printf("It's another day\n");
          }
      
          return 0;
      }
      
  5. Nested switch-case statements in C programming:

    • Description: Switch-case statements can be nested to handle more complex scenarios with multiple levels of conditions.
    • Example:
      #include <stdio.h>
      
      // Nested switch-case statements in C programming
      int main() {
          int category = 2;
          int score = 75;
      
          switch (category) {
              case 1:
                  switch (score) {
                      case 90:
                          printf("Excellent\n");
                          break;
                      case 80:
                          printf("Very Good\n");
                          break;
                      default:
                          printf("Good\n");
                  }
                  break;
              case 2:
                  printf("Category 2\n");
                  break;
              default:
                  printf("Unknown category\n");
          }
      
          return 0;
      }
      
  6. C code examples demonstrating switch-case usage:

    • Example:
      #include <stdio.h>
      
      // C code examples demonstrating switch-case usage
      int main() {
          char operator = '+';
          int num1 = 10, num2 = 5, result;
      
          switch (operator) {
              case '+':
                  result = num1 + num2;
                  printf("Sum: %d\n", result);
                  break;
              case '-':
                  result = num1 - num2;
                  printf("Difference: %d\n", result);
                  break;
              case '*':
                  result = num1 * num2;
                  printf("Product: %d\n", result);
                  break;
              case '/':
                  if (num2 != 0) {
                      result = num1 / num2;
                      printf("Quotient: %d\n", result);
                  } else {
                      printf("Cannot divide by zero.\n");
                  }
                  break;
              default:
                  printf("Invalid operator\n");
          }
      
          return 0;
      }
      
  7. Common mistakes and debugging switch-case constructs in C:

    • Common Mistake: Forgetting to use the break statement after each case, leading to fall-through.
    • Debugging Tip: Carefully review the flow of control within the switch-case and ensure proper use of break statements.
    • Example:
      #include <stdio.h>
      
      // Common mistake in switch-case and debugging tip
      int main() {
          int option = 2;
      
          switch (option) {
              case 1:
                  printf("Option 1 selected\n");
              case 2:
                  printf("Option 2 selected\n");
                  break;
              case 3:
                  printf("Option 3 selected\n");
                  break;
              default:
                  printf("Invalid option\n");
          }
      
          return 0;
      }