the switch statement is used to perform different actions based on different conditions. It's a way to make decisions in your code. Here’s how it works:

Structure of switch

switch (expression) {

    case value1:

        // Code to execute if expression == value1

        break;

    case value2:

        // Code to execute if expression == value2

        break;

    // You can have as many case statements as you want

    default:

        // Code to execute if expression doesn't match any case

}

Explanation:

  1. Expression: This is a variable or value that you want to compare. It goes inside the parentheses after switch.

  2. Case: Each case is a possible value for the expression. If the expression matches the case value, the code under that case will run.

  3. Break: The break statement is important! It tells the program to stop executing the switch block. If you forget it, the program will continue to run the next cases (this is called "fall-through").

  4. Default: This part is optional. It runs if none of the cases match the expression. Think of it as a "catch-all."

Example:

Here’s a simple example to see how it works:

#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:

  • The variable day is set to 3.
  • The switch statement checks the value of day.
  • It matches case 3, so it prints "Wednesday".
  • The break statement prevents the code from continuing to check other cases.

Summary

The switch statement is a useful tool in C for handling multiple conditions in a cleaner way compared to using many if statements. It helps make your code easier to read and maintain!

Comments

Post a Comment

Popular posts from this blog