The ‘switch’ Keyword in C Programming

C Programming @ Freshers.in

In the realm of C programming, the ‘switch’ keyword is a versatile tool for simplifying decision-making and enhancing code clarity. This comprehensive article aims to elucidate the ‘switch’ keyword, explaining its purpose, usage, and providing real-world examples with outputs. By the end, you’ll have a deep understanding of how ‘switch’ empowers you to manage control flow in your C code effectively.

The Purpose of the ‘switch’ Keyword

The ‘switch’ keyword in C is primarily used to create structured and efficient multi-branch decision-making in your code. It simplifies scenarios where you need to execute different code blocks based on the value of a particular expression.

Usage of the ‘switch’ Keyword

To utilize ‘switch,’ you define a switch statement with the ‘switch’ keyword, followed by an expression (often an integer or character). Inside the switch statement, you use ‘case’ labels to specify the possible values of the expression and the code to execute for each case.

Example 1: Basic ‘switch’ Statement

Let’s consider a simple example where we use a ‘switch’ statement to determine the day of the week based on a user-provided number:

#include <stdio.h>
int main() {
    int dayNumber;
    printf("Enter a number (1-7): ");
    scanf("%d", &dayNumber);
    switch (dayNumber) {
        case 1:
            printf("Sunday\n");
            break;
        case 2:
            printf("Monday\n");
            break;
        case 3:
            printf("Tuesday\n");
            break;
        case 4:
            printf("Wednesday\n");
            break;
        case 5:
            printf("Thursday\n");
            break;
        case 6:
            printf("Friday\n");
            break;
        case 7:
            printf("Saturday\n");
            break;
        default:
            printf("Invalid input\n");
    }
    return 0;
}

In this example, the user enters a number (1-7), and the ‘switch’ statement determines and prints the corresponding day of the week.

Example 2: Handling Multiple Cases

You can group multiple ‘case’ labels to execute the same code block for different values:

#include <stdio.h>
int main() {
    char grade;
    printf("Enter your grade (A, B, or C): ");
    scanf(" %c", &grade);
    switch (grade) {
        case 'A':
        case 'a':
            printf("Excellent\n");
            break;
        case 'B':
        case 'b':
            printf("Good\n");
            break;
        case 'C':
        case 'c':
            printf("Satisfactory\n");
            break;
        default:
            printf("Invalid grade\n");
    }
    return 0;
}

In this example, both uppercase and lowercase versions of the grade letters are handled within the same code block.

Author: user