Skip to content
Home » Embedded Systems » Embedded C » C programs on Switch-case

C programs on Switch-case

KEY TAKEAWAYS

  • Switch-case provides a clean alternative to long if-else chains for discrete value matching
  • Practice includes calculators, menu-driven programs, and day/month name lookup
  • Each case must end with break to prevent fall-through to the next case
  • The default case handles values not matched by any other case

Practice programs on Switch case

1. C program to find all roots of a quadratic equation using switch case:

#include <stdio.h>
#include <math.h> /* Used for sqrt() */

int main()
{
    float a, b, c;
    float root1, root2, imaginary;
    float discriminant;

    printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
    scanf("%f%f%f", &a, &b, &c);

    /* Calculate discriminant */
    discriminant = (b * b) - (4 * a * c);

    /* Compute roots of quadratic equation based on the nature of discriminant */
    switch(discriminant > 0)
    {
    case 1:
        /* If discriminant is positive */
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);

        printf("Two distinct and real roots exists: %.2f and %.2f",root1, root2);
        break;

    case 0:
        /* If discriminant is not positive */
        switch(discriminant < 0)
        {
            case 1:
                /* If discriminant is negative */
                root1 = root2 = -b / (2 * a);
                imaginary = sqrt(-discriminant) / (2 * a);

                printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f",root1, imaginary, root2, imaginary);
                break;

            case 0:
            /* If discriminant is zero */
                root1 = root2 = -b / (2 * a);
                printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
                break;
        }
    }

    return 0;
}

******************************************************************

2. C program to create calculator using switch case:

#include <stdio.h>

int main()
{
    char op;
    float num1, num2, result=0.0f;

    /* Print welcome message */
    printf("WELCOME TO SIMPLE CALCULATOR\n");
    printf("----------------------------\n");
    printf("Enter [number 1] [+ - * /] [number 2]\n");

    /* Input two number and operator from user */
    scanf("%f %c %f", &num1, &op, &num2);

    /* Switch the value and perform action based on operator*/
    switch(op)
    {
        case '+':
            result = num1 + num2;
            break;

        case '-':
            result = num1 - num2;
            break;

        case '*':
            result = num1 * num2;
            break;

        case '/':
            result = num1 / num2;
            break;

        default:
            printf("Invalid operator");
    }

    /* Prints the result */
    printf("%.2f %c %.2f = %.2f", num1, op, num2, result);

    return 0;
}

*******************************************************************

3. Write a Program that does the following:

User to type his own ID, if the ID is valid it will ask him to enter his password,
if the password is correct the program will print the name of the user,

otherwise ,the program will print Incorrect Password and if the ID does not exist, the program will print Incorrect ID

#include <stdio.h>
int main()
{
        int ID = 500;
        int password = 000;
        printf("Plese Enter Your ID:n ");
        scanf("%d", & ID);
        switch (ID)
        {
            case 500:
                printf("Enter your password:n ");
                scanf("%d", &password);
                switch (password)
                {
                    case 000:
                        printf("Welcome Dear Programme\r\n");
                        break;
                    default:
                        printf("incorrect password");
                        break;
                }
                break;
            default:
                printf("incorrect ID");
                break;
        }
}

********************************************************************

For more practice questions, go to  Questionnare.


Understanding Switch-Case in C

The switch statement evaluates an expression once and compares its value against multiple case labels. When a match is found, the corresponding block executes. Unlike if-else chains, switch-case produces cleaner machine code because the compiler can use a jump table for constant integer values.

When to use switch-case over if-else:

  • The variable is compared against discrete constant values (not ranges)
  • There are 3 or more cases to handle
  • You want cleaner, more readable code than nested if-else

Explanation of the Programs Above

Program 1: Quadratic Equation Solver

This program uses a clever trick — switch(discriminant > 0) evaluates to 1 (true) or 0 (false). When the discriminant is positive, two real roots exist. When it is zero, both roots are equal. When negative, we get complex roots with imaginary parts. The nested switch handles the zero-vs-negative distinction.

Key concept: Switch-case works with integer expressions. The comparison discriminant > 0 returns an integer (0 or 1), making it valid for switch.

Program 2: Simple Calculator

This is the classic switch-case use case — matching a character (+, -, *, /) to an operation. The default case catches invalid operators. Note that char is an integer type in C, so switch works directly with character values.

Key concept: Each case must end with break. Without it, execution “falls through” to the next case — a common source of bugs.

Program 3: ID and Password Validation

This demonstrates nested switch statements. The outer switch validates the user ID, and only if it matches, the inner switch checks the password. While this works for a small demo, real authentication systems would use arrays or hash tables instead of hardcoded switch cases.

More Practice Programs

4. Day of the Week from Number

Given a number 1–7, print the corresponding day name. This is the most natural use of switch-case — mapping integers to values.

#include <stdio.h>

int main(void)
{
    int day;

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

    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 number. Enter 1-7.\n");
            break;
    }

    return 0;
}

Output:

Enter day number (1-7): 3
Wednesday

5. Menu-Driven Embedded System Simulator

This program simulates a simple embedded device menu — reading a sensor, toggling an LED, or checking battery. It demonstrates how switch-case is used in real embedded firmware for command processing.

#include <stdio.h>

int main(void)
{
    int choice;
    int led_state = 0;

    printf("=== Device Menu ===\n");
    printf("1. Read Temperature Sensor\n");
    printf("2. Toggle LED\n");
    printf("3. Check Battery Level\n");
    printf("4. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            /* In real firmware: read ADC register */
            printf("Temperature: 25.3 C (simulated ADC read)\n");
            break;

        case 2:
            led_state = !led_state;
            printf("LED is now %s\n", led_state ? "ON" : "OFF");
            break;

        case 3:
            /* In real firmware: read battery voltage via ADC */
            printf("Battery: 3.7V (82%%)\n");
            break;

        case 4:
            printf("Shutting down...\n");
            break;

        default:
            printf("Unknown command. Valid options: 1-4\n");
            break;
    }

    return 0;
}

Output:

=== Device Menu ===
1. Read Temperature Sensor
2. Toggle LED
3. Check Battery Level
4. Exit
Enter choice: 2
LED is now ON

6. Character Type Classifier (Fall-Through Example)

This program demonstrates intentional fall-through — grouping multiple case labels that share the same action. It classifies a character as a vowel, consonant, digit, or special character.

#include <stdio.h>
#include <ctype.h>

int main(void)
{
    char ch;

    printf("Enter a character: ");
    scanf(" %c", &ch);

    switch (tolower(ch)) {
        /* Vowels — intentional fall-through */
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("'%c' is a vowel\n", ch);
            break;

        /* Digits */
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            printf("'%c' is a digit\n", ch);
            break;

        default:
            if (isalpha(ch)) {
                printf("'%c' is a consonant\n", ch);
            } else {
                printf("'%c' is a special character\n", ch);
            }
            break;
    }

    return 0;
}

Output:

Enter a character: E
'E' is a vowel

Key concept: When multiple case labels appear without a break between them, execution falls through to the next case. Here, all five vowel cases share the same printf. This is the one situation where omitting break is intentional and useful.

Common Mistakes with Switch-Case

1. Forgetting the break Statement

The most common switch-case bug. Without break, execution falls through to the next case:

/* BUG: Missing break causes fall-through */
switch (command) {
    case 1:
        start_motor();
        /* Missing break! */
    case 2:
        stop_motor();  /* This runs for command=1 too! */
        break;
}

/* FIX: Always add break */
switch (command) {
    case 1:
        start_motor();
        break;          /* Now case 2 won't execute */
    case 2:
        stop_motor();
        break;
}

2. Using Variables in Case Labels

Case labels must be compile-time constants. Variables or function calls are not allowed:

int threshold = 10;

/* ERROR: case label is not a constant */
switch (value) {
    case threshold:       /* Won't compile! */
        printf("Match\n");
        break;
}

/* FIX: Use a #define or const with known value */
#define THRESHOLD 10
switch (value) {
    case THRESHOLD:       /* OK — preprocessor constant */
        printf("Match\n");
        break;
}

3. Forgetting the default Case

Always include a default case to catch unexpected values. In embedded systems, an unhandled command could leave the system in an undefined state:

/* RISKY: No default — what happens if mode is 3? */
switch (mode) {
    case 0: idle();    break;
    case 1: run();     break;
    case 2: sleep();   break;
}

/* SAFE: default catches unexpected values */
switch (mode) {
    case 0: idle();    break;
    case 1: run();     break;
    case 2: sleep();   break;
    default:
        error_handler(INVALID_MODE);
        break;
}

4. Using Floating-Point in Switch

Switch only works with integer types (int, char, enum). Floating-point values are not allowed:

float voltage = 3.3;
/* ERROR: float not allowed in switch */
switch (voltage) {        /* Won't compile! */
    case 3.3: /* ... */ break;
}
/* FIX: Use if-else for floating-point comparisons */
if (voltage > 3.0 && voltage < 3.6) {
    /* 3.3V logic level */
}

Related Articles

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *