-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitch.cpp
More file actions
103 lines (86 loc) · 2.76 KB
/
Copy pathswitch.cpp
File metadata and controls
103 lines (86 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
using namespace std;
int main() {
// ===================================================
// 1. BASIC SWITCH STATEMENT
// ===================================================
int day = 4;
cout << "=== 1. BASIC SWITCH STATEMENT ===" << endl;
// The switch expression is evaluated once and compared with each case
switch (day) {
case 1:
cout << "Monday" << endl;
break; // Exits the switch block if matched
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl; // Matched! Outputs "Thursday"
break;
case 5:
cout << "Friday" << endl;
break;
default:
cout << "Weekend" << endl; // Optional: Executes if no case matches
}
// ===================================================
// 2. THE 'default' KEYWORD
// ===================================================
int unknownDay = 9;
cout << "\n=== 2. THE DEFAULT KEYWORD ===" << endl;
switch (unknownDay) {
case 6:
cout << "Saturday" << endl;
break;
case 7:
cout << "Sunday" << endl;
break;
default:
// Runs when 'unknownDay' doesn't match any case above
cout << "Invalid day number!" << endl;
}
// ===================================================
// 3. FALL-THROUGH BEHAVIOR (OMITTING 'break')
// ===================================================
int dayType = 6; // 6 = Saturday
cout << "\n=== 3. FALL-THROUGH (MULTIPLE CASES) ===" << endl;
switch (dayType) {
// Grouping multiple cases together by omitting 'break'
case 1:
case 2:
case 3:
case 4:
case 5:
cout << "Weekday" << endl;
break;
case 6:
case 7:
cout << "Weekend!" << endl; // Matches case 6 and executes this
break;
default:
cout << "Invalid day" << endl;
}
// ===================================================
// 4. SWITCH WITH 'char' DATA TYPE
// ===================================================
char grade = 'B';
cout << "\n=== 4. SWITCH WITH CHAR ===" << endl;
// Switch also works with integral types like char, int, enum
switch (grade) {
case 'A':
cout << "Excellent!" << endl;
break;
case 'B':
cout << "Good job!" << endl; // Outputs "Good job!"
break;
case 'C':
cout << "Fair" << endl;
break;
default:
cout << "Needs improvement" << endl;
}
return 0;
}