Write a program to print corresponding day based on given input
Definition:
A switch
statement is a multi-way branching control structure that allows you to execute different code blocks based on the value of a single expression.
Basic Syntax:
switch (expression) {
case value1:
// code to execute if expression == value1
break;
case value2:
// code to execute if expression == value2
break;
default:
// code to execute if no case matches
break;
}
Key Components:
When to use switch?
❌ Using If-Else (Verbose & Repetitive):
if (day == 0) {
cout << "Sunday";
} else if (day == 1) {
cout << "Monday";
} else if (day == 2) {
cout << "Tuesday";
} else if (day == 3) {
cout << "Wednesday";
} else if (day == 4) {
cout << "Thursday";
} else if (day == 5) {
cout << "Friday";
} else if (day == 6) {
cout << "Saturday";
} else {
cout << "Invalid";
}
Problems: Repetitive, variable checked 7 times, harder to read
✅ Using Switch (Clean & Efficient):
switch (day) {
case 0: cout << "Sunday"; break;
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
case 3: cout << "Wednesday"; break;
case 4: cout << "Thursday"; break;
case 5: cout << "Friday"; break;
case 6: cout << "Saturday"; break;
default: cout << "Invalid"; break;
}
Benefits: Cleaner, expression evaluated once, easier to maintain
Performance Comparison:
Aspect | If-Else Chain | Switch Statement |
---|---|---|
Readability | Gets messy with many conditions | Very clean and structured |
Evaluation | Checks each condition sequentially | Evaluates expression once |
Performance | O(n) - linear search | O(1) - jump table (compiler optimization) |
Maintainability | Hard to add/modify cases | Easy to add new cases |
Use Case | Complex conditions, ranges | Equality checks, discrete values |
💡 Compiler Optimization:
Compilers often optimize switch statements into jump tables (array of addresses), making them much faster than if-else chains for many cases!
What does break
do?
The break
statement immediately exits the switch block, preventing "fall-through" to subsequent cases.
❌ Without break (WRONG - Fall-through bug!):
switch (day) {
case 0: cout << "Sunday"; // No break!
case 1: cout << "Monday"; // No break!
case 2: cout << "Tuesday"; // No break!
}
Input: 0
Output: SundayMondayTuesday
❌ WRONG!
Execution continues through all cases below!
✅ With break (CORRECT):
switch (day) {
case 0: cout << "Sunday"; break; // Exits switch
case 1: cout << "Monday"; break;
case 2: cout << "Tuesday"; break;
}
Input: 0
Output: Sunday
✅ CORRECT!
⚠️ CRITICAL RULE:
Always include break
after each case (unless intentional fall-through)
When is fall-through useful?
switch (month) {
case 12:
case 1:
case 2:
cout << "Winter";
break; // Only one break for all three
case 3:
case 4:
case 5:
cout << "Spring";
break;
}
This groups multiple cases that share the same action!
Common Mistakes:
Mistake | Result | Fix |
---|---|---|
Forgot break |
Fall-through to next case | Add break; at end of each case |
break before code |
Code never executes | Put break after code |
No break in default |
Continues to code after switch | Add break; in default too |
What is default
?
The default
case executes when no other case matches. It's like the else
in an if-else chain.
❌ Without default:
switch (day) {
case 0: cout << "Sunday"; break;
case 1: cout << "Monday"; break;
// ... only 0-6
}
Input: 99
Output: (nothing printed!) ❌ Silent failure
✅ With default:
switch (day) {
case 0: cout << "Sunday"; break;
case 1: cout << "Monday"; break;
// ... only 0-6
default: cout << "Invalid"; break;
}
Input: 99
Output: Invalid
✅ Handles invalid input!
Why default matters:
Best Practices:
default
case (even if you think you've covered everything)default
for error handling or loggingdefault
at the end (convention, but can be anywhere)break
in default too (good habit)Real-world example:
switch (userChoice) {
case 1: processOrder(); break;
case 2: viewCart(); break;
case 3: checkout(); break;
default:
cout << "Invalid option! Please choose 1-3.";
break;
}
Our declaration:
long long day;
Question: Why long long
for a day number (0-6)?
Answer: The constraint says:
1 <= day_num <= 10^15
Data type ranges:
Type | Size | Max Value | Can Handle 10^15? |
---|---|---|---|
int |
4 bytes | ~2 × 10^9 | ❌ Too small! |
long |
4 bytes* | ~2 × 10^9 | ❌ Same as int! |
long long |
8 bytes | ~9 × 10^18 | ✅ Perfect! |
* On most systems, long
= int
(4 bytes)
Why the huge constraint?
The problem allows ANY number as input, even though valid days are only 0-6. This tests:
default
case in your switchWhat happens if you use int
?
int day;
cin >> day; // Input: 10000000000000 (10^13)
Result: Integer overflow! The value wraps around and becomes negative or garbage!
Practical note:
In real applications, day numbers would be 0-6, but for competitive programming, always check constraints and choose appropriate data types!
Example 1: Valid input (day = 3)
long long day;
cin >> day;
→ User enters 3
switch (day)
evaluates to switch (3)
case 0:
→ 3 != 0, skipcase 1:
→ 3 != 1, skipcase 2:
→ 3 != 2, skipcase 3:
→ 3 == 3, MATCH! ✅cout << "Wednesday";
break;
→ Exit switchreturn 0;
→ Program endsExample 2: Invalid input (day = 10)
long long day;
cin >> day;
→ User enters 10
switch (day)
evaluates to switch (10)
case 0:
→ 10 != 0, skipcase 1:
→ 10 != 1, skipdefault:
cout << "Invalid";
break;
→ Exit switchreturn 0;
→ Program endsExample 3: Edge case (day = 0)
day = 0
switch (0)
case 0:
→ MATCH immediately! ✅cout << "Sunday";
Key Observations:
break
prevents checking remaining casesdefault
only executes if no case matches1. Switch Limitations:
2. What can you use in switch?
int
, long
, long long
, short
char
(characters)enum
(enumerations)3. Character switch example:
char grade;
cin >> grade;
switch (grade) {
case 'A': cout << "Excellent!"; break;
case 'B': cout << "Good!"; break;
case 'C': cout << "Average"; break;
default: cout << "Fail"; break;
}
4. Case grouping (intentional fall-through):
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
cout << "Weekday";
break;
case 0:
case 6:
cout << "Weekend";
break;
}
5. Nested switch statements:
switch (category) {
case 1:
switch (subCategory) {
case 'A': /* ... */ break;
case 'B': /* ... */ break;
}
break;
case 2:
// ...
}
⚠️ Use sparingly - can get confusing!
6. Modern C++ alternative (C++17+):
// Using if-constexpr with string comparison
if (day == "Monday") { /* ... */ }
else if (day == "Tuesday") { /* ... */ }
Or use std::map
for string-to-action mapping!
Where switch statements are commonly used:
1. Menu-Driven Programs:
cout << "1. New Game\n2. Load Game\n3. Settings\n4. Exit\n";
int choice;
cin >> choice;
switch (choice) {
case 1: startNewGame(); break;
case 2: loadGame(); break;
case 3: openSettings(); break;
case 4: exit(0); break;
default: cout << "Invalid choice!"; break;
}
2. Calculator Operations:
switch (operator) {
case '+': result = a + b; break;
case '-': result = a - b; break;
case '*': result = a * b; break;
case '/': result = a / b; break;
default: cout << "Invalid operator"; break;
}
3. State Machines:
4. Event Handling:
switch (eventType) {
case MOUSE_CLICK: handleClick(); break;
case KEY_PRESS: handleKeyPress(); break;
case WINDOW_RESIZE: handleResize(); break;
}
5. HTTP Response Codes:
switch (statusCode) {
case 200: return "OK";
case 404: return "Not Found";
case 500: return "Server Error";
}
6. Month/Day Calculations:
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31; break;
case 4: case 6: case 9: case 11:
days = 30; break;
case 2:
days = isLeapYear ? 29 : 28; break;
}
💡 Industry Tip: Switch statements are heavily used in embedded systems, game development, and system programming for efficient state management!
💡 Key Takeaway: Switch is perfect for multiple equality checks on a single variable. Always use break
to prevent fall-through, and include a default
case for robust error handling!
#include <iostream>
using namespace std;
int main() {
long long day;
cin >> day;
switch (day) {
case 0:
cout << "Sunday";
break;
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
default:
cout << "Invalid";
break;
}
return 0;
}