Switch

Switch/Case
A switch statement is a glorified if-else chain that compares the initial value to each case, if it matches up, then the content of the case is executed until it reaches a break point. This can only be done with a limited number of data types: int and char. The use of a break point is important if not otherwise intended because the absence of a break point results in 'fall-through' to the next case, an example where this could be intentional is shown in C++ below. There is a special case called 'default' that will act as the case for anything, so it is often used to report errors in input.

In Java
code format="java" public class Main{ public static void main(String[] args){ char symbol = '*'; int x, y;       x = y = 5; switch(symbol){ //the switch now jumps to the case '*' case '+': x += y;               break; case '-': x -= y;               break; case '*': //and executes until x *= y;               break; //the break; case '/': x /= y;               break; }       //x is now 25 } } code

In C++
code format="cpp"
 * 1) include

int main{ int x = 4; switch(x){ //the switch now jumps to case 4 case 0: printf("You typed zero.\n"); break; case 4: //and executes until printf("x is an even number.\n"); case 1: //fall through case 9: //fall through printf("x is a perfect square.\n"); break; //the break; case 2: printf("x is an even number.\n"); case 3: case 5: case 7: printf("x is a prime number.\n"); break; case 6: case 8: printf("x is an even number.\n"); break; default: printf("x is not a single-digit number.\n"); break; }

return 0; } code code Output: x is an even number. x is a perfect square. code