switch(expression){case value1://code to execute;break; //optionalcase value2://code to execute;break; //optional......default://code to execute if all cases do not match;}
👇 Click to receive 👇
Rules of the Switch Statement in C
-
The switch expression must be of integer or character type. -
The case values must be integer or character constants. -
The case values can only be used within the switch statement. -
The break statement in switch cases is optional. If no break statement is found in a case, all subsequent cases after the matching case will be executed. This is known as the “fall-through” behavior of the switch statement in C.
int x, y, z;char a, b;float f;
How the Switch Case Statement Works
#include<stdio.h>
int main() { int number = 0; printf("Please enter a number: "); scanf("%d", &number); switch(number) { case 10: printf("Number equals 10"); break; case 50: printf("Number equals 50"); break; case 100: printf("Number equals 100"); break; default: printf("Number does not equal 10, 50, or 100"); } return 0;}
Please enter a number: 4Number does not equal 10, 50, or 100Please enter a number: 50Number equals 50
#include <stdio.h>
int main() { int x = 10, y = 5; switch (x > y && x + y > 0) { case 1: printf("hi"); break; case 0: printf("bye"); break; default: printf("Hello bye"); } return 0;}
hi