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
- We declare two variables,
x
andy
, and assign them the values 2 and 3, respectively. - The outer switch statement is based on the value of
x
. - Inside the outer switch statement, we have multiple cases:
- If
x
is 1, we enter the inner switch statement. - If
x
is 2, we print "x is 2" and exit the switch statement. - If
x
is neither 1 nor 2, we print "x is neither 1 nor 2" and exit the switch statement. - Inside the inner switch statement, we have multiple cases based on the value of
y
. - If
y
is 1, we print "y is 1" and exit the switch statement. - If
y
is 2, we print "y is 2" and exit the switch statement. - 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.