The switch statement selects one branch from several constant choices. It is useful when one expression is compared against discrete values such as menu numbers, characters or status codes.
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// no case matched
break;
}
case labels must be constant integral expressions. The optional default branch runs when no case matches.
Without break, execution continues into the following case. This behavior is called fall-through. Use it only when several cases intentionally share the same code.
#include <stdio.h>
int main(void) {
char grade;
printf("Enter grade A to D: ");
grade = (char)getchar();
switch (grade) {
case 'A':
printf("You got A grade.\n");
break;
case 'B':
printf("You got B grade.\n");
break;
case 'C':
printf("You got C grade.\n");
break;
case 'D':
printf("You got D grade.\n");
break;
default:
printf("Unknown grade.\n");
break;
}
return 0;
}
Key change: several case labels can intentionally fall through to one shared statement block.
#include <stdio.h>
int main(void) {
int day = 5;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
printf("It is a weekday.\n");
break;
case 6:
case 7:
printf("It is the weekend.\n");
break;
default:
printf("Invalid day.\n");
break;
}
return 0;
}
Output
It is a weekday.
#include <stdio.h>
int main(void) {
int num1, num2, choice;
printf("Enter two integers: ");
if (scanf("%d %d", &num1, &num2) != 2) {
printf("Invalid input.\n");
return 1;
}
printf("1. Add\n2. Subtract\n3. Multiply\n4. Divide\n");
printf("Choose an operation: ");
if (scanf("%d", &choice) != 1) {
printf("Invalid choice.\n");
return 1;
}
switch (choice) {
case 1:
printf("Result: %d\n", num1 + num2);
break;
case 2:
printf("Result: %d\n", num1 - num2);
break;
case 3:
printf("Result: %d\n", num1 * num2);
break;
case 4:
if (num2 != 0) {
printf("Result: %.2f\n", (double)num1 / num2);
} else {
printf("Cannot divide by zero.\n");
}
break;
default:
printf("Invalid choice.\n");
break;
}
return 0;
}
switch for several exact integral/character choices.if...else for ranges, compound logical conditions and comparisons such as x > 10.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.