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 C++ 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 C++ switch case statement gives easy-to-match conditions & easy readability.
- The C++ switch case statement checks faster rather than the if..else if...else ladder.
Syntax of the C++ switch case statement
switch (e) {
case constant1:
// statements 1
break;
case constant2:
// statements 2
break;
.
.
.
default:
// default statements
}
The C++ switch case statement execution flow
- The C++ switch parameter matches conditions in every case to make a decision.
- There is if any case will be matched with the switch parameter then switch condition checking will be automatically stopped.
- There is 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 a C++ example:
// C++ program of decision making by using the switch case statement
#include <iostream>
using namespace std;
int main() {
int w;
cout << "Enter the week number among 1 to 7\n";
cin >> w;
if (w) {
switch (w) {
case 1:
cout << "Hi\nIt's sunday on today, It's the week-off day.\n";
break;
case 2:
cout << "Hi\nIt's monday on today, It's the working day.\n";
break;
case 3:
cout << "Hi\nIt's tuesday on today, It's the working day.\n";
break;
case 4:
cout << "Hi\nIt's wednesday on today, It's the working day.\n";
break;
case 5:
cout << "Hi\nIt's thursday on today, It's the working day.\n";
break;
case 6:
cout << "Hi\nIt's friday on today, It's the working day.\n";
break;
case 7:
cout << "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:
cout << "Sorry, You entered the wrong week number, Kindly try again\n";
}
} else {
cout << "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.