Skip to content

C_Switch.c

ani9977 edited this page Sep 11, 2024 · 1 revision

Here’s the updated C code with added documentation and an explanation:

#include <stdio.h>

/**
 * @brief The main function demonstrates the use of a switch statement.
 * 
 * This function uses a switch statement to print the name of the day corresponding to the integer value of 'day'.
 * 
 * @return int Returns 0 to indicate successful execution.
 */
int main() {
    int day = 3;  /**< Integer variable representing the day of the week. */

    // Switch statement to determine and print the day of the week
    switch (day) {
        case 1:
            printf("Monday\n");   /**< Prints "Monday" if day is 1. */
            break;               /**< Exits the switch statement after the case is executed. */
        case 2:
            printf("Tuesday\n");  /**< Prints "Tuesday" if day is 2. */
            break;               /**< Exits the switch statement after the case is executed. */
        case 3:
            printf("Wednesday\n");/**< Prints "Wednesday" if day is 3. */
            break;               /**< Exits the switch statement after the case is executed. */
        default:
            printf("Other day\n");/**< Prints "Other day" for any value not explicitly handled by the cases. */
    }

    return 0;   /**< Return 0 to indicate successful execution. */
}

Explanation

  1. Variable Initialization:

    • int day = 3; declares an integer variable day and initializes it with the value 3.
  2. Switch Statement:

    • switch (day) evaluates the variable day and compares it with each case label.
    • case 1: checks if day equals 1 and prints "Monday". The break statement exits the switch block to prevent fall-through to subsequent cases.
    • case 2: checks if day equals 2 and prints "Tuesday". The break statement exits the switch block.
    • case 3: checks if day equals 3 and prints "Wednesday". The break statement exits the switch block.
    • default: handles any values not explicitly covered by the cases, printing "Other day".
  3. Return Statement:

    • return 0; indicates that the program has executed successfully. The value 0 is returned to the operating system.

Clone this wiki locally