Nested Switch

Nested Switch

In C programming language, you can use nested switch statements to create more complex conditional logic. A nested switch statement is simply a switch statement inside another switch statement. The syntax of a nested switch statement is as follows:Bottom of Form

				
					switch (expression1) {
    case value1:
                                // code to execute when expression1 equals value1
        switch (expression2) {
            case value2:
                                  // code to execute when both expression1 and                                                 expression2 are true
                break;
            case value3:
                                 // code to execute when expression1 is true and expression2 is false
                break;
            default:
                                 // code to execute when expression2 doesn't match any of the values
                break;
        }
        break;
    case value4:
                                // code to execute when expression1 equals value4
        break;
    default:
                      // code to execute when expression1 doesn't match any of the values
        break;
}

				
			

Here, the inner switch statement is only executed if the outer switch statement’s expression matches a certain case value. If the inner switch statement’s expression matches a case value, its corresponding code block is executed. Otherwise, the default label of the inner switch statement is executed. If the outer switch statement’s expression doesn’t match any of the case values, its default label is executed.

For example, let’s say we have an integer variable month that stores the month of the year as a number (1-12), and we want to print a message that says the number of days in the month, based on whether it is a leap year or not. We can use nested switch statements as follows:

				
					switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        // these months have 31 days
        printf("There are 31 days in this month.\n");
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        // these months have 30 days
        printf("There are 30 days in this month.\n");
        break;
    case 2:
        // February has 28 days in a non-leap year and 29 days in a leap year
        switch (isLeapYear) {
            case 1:
                printf("There are 29 days in this month.\n");
                break;
            default:
                printf("There are 28 days in this month.\n");
                break;
        }
        break;
    default:
        printf("Invalid month number.\n");
        break;
}


				
			
Join To Get Our Newsletter
Spread the love