nested switch case in c

Nested Switch Case in C

Here is an example of a nested switch case in C:

#include <stdio.h>

int main() {
   int x = 2;
   int y = 3;

   switch (x) {
      case 1:
         printf("x is 1\n");
         switch (y) {
            case 1:
               printf("y is 1\n");
               break;
            case 2:
               printf("y is 2\n");
               break;
            default:
               printf("y is neither 1 nor 2\n");
         }
         break;
      case 2:
         printf("x is 2\n");
         break;
      default:
         printf("x is neither 1 nor 2\n");
   }

   return 0;
}

Explanation

  1. We declare two variables, x and y, and assign them the values 2 and 3, respectively.
  2. The outer switch statement is based on the value of x.
  3. Inside the outer switch statement, we have multiple cases:
  4. If x is 1, we enter the inner switch statement.
  5. If x is 2, we print "x is 2" and exit the switch statement.
  6. If x is neither 1 nor 2, we print "x is neither 1 nor 2" and exit the switch statement.
  7. Inside the inner switch statement, we have multiple cases based on the value of y.
  8. If y is 1, we print "y is 1" and exit the switch statement.
  9. If y is 2, we print "y is 2" and exit the switch statement.
  10. If y is neither 1 nor 2, we print "y is neither 1 nor 2" and exit the switch statement.

In this example, the output will be "x is 2" because the value of x is 2 and the value of y is not relevant to the outer switch statement.

I hope this explanation helps! Let me know if you have any further questions.