12. Print Day of Week

Easy ⏱️ 10 min

Problem Statement

Write a program to print corresponding day based on given input

Input Format:
Accept integer as a input
Output Format:
Print corresponding day(0-6) or "Invalid" day- Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
Constraints:
1 <= day_num <= 10^15
Sample Input 1:
0
Sample Output 1:
Sunday
Sample Input 2:
6
Sample Output 2:
Saturday
🔀 Mastering the Switch Statement
🎯 What is a Switch Statement?

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:

  • Expression: Evaluated once at the start (must be integer or enumeration type)
  • Case labels: Constant values to compare against
  • Break statement: Exits the switch block
  • Default case: Catches all unmatched values (optional but recommended)

When to use switch?

  • ✅ Multiple equality comparisons against a single variable
  • ✅ Fixed set of discrete values (enums, menu choices, days, etc.)
  • ✅ Better readability than many if-else statements
  • ❌ Range checks (use if-else instead)
  • ❌ Complex conditions (use if-else instead)
  • ❌ String comparisons in C++ (use if-else or maps)
🚦 Switch vs If-Else: The Showdown

❌ 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!

⚠️ The Break Statement - Critical!

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: SundayMondayTuesdayWRONG!

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: SundayCORRECT!

⚠️ 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
🎭 The Default Case - Your Safety Net

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:

  • Input Validation: Catches invalid/unexpected values
  • User Feedback: Informs user about errors
  • Debugging: Helps identify unexpected values during testing
  • Robustness: Makes program more reliable
  • Future-Proofing: Handles cases you didn't anticipate

Best Practices:

  • Always include a default case (even if you think you've covered everything)
  • Use default for error handling or logging
  • Place default at the end (convention, but can be anywhere)
  • Include 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;
}

🔢 Why long long? Understanding Data Types

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:

  • Your ability to choose correct data types
  • Input validation (handling invalid inputs)
  • The default case in your switch

What 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!

🔍 Step-by-Step Execution

Example 1: Valid input (day = 3)

  1. Declare: long long day;
  2. Read: cin >> day; → User enters 3
  3. Enter switch: switch (day) evaluates to switch (3)
  4. Compare against cases:
    • case 0: → 3 != 0, skip
    • case 1: → 3 != 1, skip
    • case 2: → 3 != 2, skip
    • case 3: → 3 == 3, MATCH! ✅
  5. Execute: cout << "Wednesday";
  6. Break: break; → Exit switch
  7. Continue: return 0; → Program ends
  8. Output: "Wednesday"

Example 2: Invalid input (day = 10)

  1. Declare: long long day;
  2. Read: cin >> day; → User enters 10
  3. Enter switch: switch (day) evaluates to switch (10)
  4. Compare against all cases:
    • case 0: → 10 != 0, skip
    • case 1: → 10 != 1, skip
    • ... all cases 2-6 don't match ...
  5. No match found → Jump to default:
  6. Execute: cout << "Invalid";
  7. Break: break; → Exit switch
  8. Continue: return 0; → Program ends
  9. Output: "Invalid"

Example 3: Edge case (day = 0)

  1. Read: day = 0
  2. Enter switch: switch (0)
  3. First case: case 0:MATCH immediately! ✅
  4. Execute: cout << "Sunday";
  5. Break: Exit before checking any other cases
  6. Output: "Sunday"

Key Observations:

  • The expression is evaluated only once
  • Cases are checked sequentially until a match
  • break prevents checking remaining cases
  • default only executes if no case matches
💡 Advanced Switch Concepts

1. Switch Limitations:

  • ❌ Cannot use floating-point values (float, double)
  • ❌ Cannot use strings directly in C++ (can in Java, JavaScript)
  • ❌ Cannot use variables as case values (must be constants)
  • ❌ Cannot use ranges (e.g., case 1-5:)

2. What can you use in switch?

  • int, long, long long, short
  • char (characters)
  • enum (enumerations)
  • ✅ Constant integer expressions

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!

🌍 Real-World Applications

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:

  • Game states (menu, playing, paused, game over)
  • Traffic light controllers
  • Vending machines
  • Protocol handlers (networking)

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!

Solution

#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;
}