C program of decision making by using the switch case statement
ADVERTISEMENTS
C program of decision making by using the switch case statement, In this program you will learn how to make decisions by using a switch case statement.
- The switch case statement is the same as the if..else if...else ladder in which the if..else if...else ladder making a decision among several conditions.
- The switch case statement gives easy-to-match conditions & easy readability.
- The switch case statement checks faster rather than the if..else if...else ladder.
Syntax of the switch case statement
switch (e) {
case constant1:
// statements 1
break;
case constant2:
// statements 2
break;
.
.
.
default:
// default statements
}
The switch case statement execution flow
- This switch parameter matches conditions in every case to make a decision.
- if any case will be matched with the switch parameter then switch condition checking will be automatically stopped.
- If any cases don't match the condition then It navigates to the default case and the switch will be stopped.
Let us understand this statement through an example:
// C program of decision making by using the switch case statement
#include <stdio.h>
int main() {
int w;
printf("Enter the week number among 1 to 7\n");
scanf("%d", &w);
if (w) {
switch (w) {
case 1:
printf("Hi\nIt's sunday on today, It's the week-off day.\n");
break;
case 2:
printf("Hi\nIt's monday on today, It's the working day.\n");
break;
case 3:
printf("Hi\nIt's tuesday on today, It's the working day.\n");
break;
case 4:
printf("Hi\nIt's wednesday on today, It's the working day.\n");
break;
case 5:
printf("Hi\nIt's thursday on today, It's the working day.\n");
break;
case 6:
printf("Hi\nIt's friday on today, It's the working day.\n");
break;
case 7:
printf("Hi\nIt's saturday on today, It's the week-off day.\n");
break;
// w parameter doesn't match any case constant then It navigates to default:
default:
printf("Sorry, You entered the wrong week number, Kindly try again\n");
}
} else {
printf("Sorry didn't entered any week number!\n");
}
return 0;
}
Output
Enter the week number among 1 to 7
7
Hi
It's saturday on today, It's the week-off day.
7
Hi
It's saturday on today, It's the week-off day.