13. Print Month Name

Easy ⏱️ 10 min

Problem Statement

Write a program to print the respective month name based on the given input

Input Format:
Accept an integer as a input
Output Format:
Print respective month or "Invalid" month names - January,February,March,April,May,June,July,August,September,October,November,December
Constraints:
1 <= month_num <= 10^15
Sample Input 1:
12
Sample Output 1:
December
Sample Input 2:
24
Sample Output 2:
Invalid
📅 Switch with 12 Cases - Pattern Recognition
🎯 Scaling Switch Statements - From 7 to 12 Cases

Progression of complexity:

  • Previous problem: 7 cases (days: 0-6)
  • This problem: 12 cases (months: 1-12)
  • Same pattern, more cases!

Key difference: Starting from 1 instead of 0!

Concept Days (Previous) Months (This)
Index Range 0-6 (zero-based) 1-12 (one-based)
Total Cases 7 + default = 8 12 + default = 13
First Case case 0: case 1:
Invalid Values <0 or >6 <1 or >12

Why months start at 1, not 0?

  • 📅 Human convention: We say "January is month 1" not "month 0"
  • 📅 Calendar systems: Gregorian calendar uses 1-12
  • 📅 Real-world usage: Dates written as MM/DD/YYYY (01-12)
  • 💻 Programming: Arrays start at 0, but months are human-facing!

Pattern recognition:

Switch statements work great for any fixed mapping:

  • Days: 0-6 → 7 cases
  • Months: 1-12 → 12 cases
  • Grades: A-F → 5-6 cases
  • Menu options: 1-N → N cases
📆 The Gregorian Calendar System

Why 12 months?

The Gregorian calendar (established 1582) divides the year into 12 months based on:

  • 🌙 Lunar cycles: ~12.37 full moons per solar year
  • ⏰ Roman calendar: Originally 10 months, later expanded to 12
  • 🌍 Solar year: 365.25 days divided into manageable chunks

Month origins and meanings:

# Month Days Origin/Meaning
1 January 31 Janus (god of beginnings)
2 February 28/29 Februa (purification festival)
3 March 31 Mars (god of war)
4 April 30 Aperire (to open - spring)
5 May 31 Maia (goddess of growth)
6 June 30 Juno (goddess of marriage)
7 July 31 Julius Caesar
8 August 31 Augustus Caesar
9 September 30 Septem (seven - originally 7th)
10 October 31 Octo (eight - originally 8th)
11 November 30 Novem (nine - originally 9th)
12 December 31 Decem (ten - originally 10th)

🤔 Fun fact: September through December literally mean "seventh" through "tenth" because the Roman calendar originally started with March!

🔍 Step-by-Step Execution Examples

Example 1: Valid month (input = 12)

  1. Declare: long long month;
  2. Read: cin >> month; → User enters 12
  3. Enter switch: switch (month)switch (12)
  4. Compare cases sequentially:
    • case 1: → 12 ≠ 1, skip
    • case 2: → 12 ≠ 2, skip
    • ... (cases 3-11 skipped) ...
    • case 12: → 12 == 12, MATCH! ✅
  5. Execute: cout << "December";
  6. Break: break; → Exit switch
  7. Output: "December"

Example 2: First month (input = 1)

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

Example 3: Invalid input (input = 24)

  1. Read: month = 24
  2. Enter switch: switch (24)
  3. Check all cases:
    • case 1: → 24 ≠ 1, skip
    • case 2: → 24 ≠ 2, skip
    • ... all 12 cases don't match ...
  4. No match found → Jump to default:
  5. Execute: cout << "Invalid";
  6. Break: Exit switch
  7. Output: "Invalid"

Example 4: Edge case (input = 0)

  1. Read: month = 0
  2. Enter switch: switch (0)
  3. Check all cases: None match (0 < 1)
  4. Jump to default:
  5. Output: "Invalid"

Example 5: Negative input (input = -5)

  1. Read: month = -5
  2. Enter switch: switch (-5)
  3. No case matches negative numbers
  4. Jump to default:
  5. Output: "Invalid"
⚡ Efficiency: Why Switch Beats If-Else Here

Imagine using if-else for 12 months:

if (month == 1) {
  cout << "January";
} else if (month == 2) {
  cout << "February";
} else if (month == 3) {
  cout << "March";
}
// ... 9 more else-if blocks!
else if (month == 12) {
  cout << "December";
} else {
  cout << "Invalid";
}

Problems with if-else approach:

  • Verbose: 12 separate condition checks
  • Repetitive: month == written 12 times
  • Slow: For month=12, checks all 12 conditions sequentially
  • Hard to maintain: Scrolling through 40+ lines
  • Error-prone: Easy to forget else or mistype variable

Switch advantages:

  • Compact: 12 cases in ~30 lines (vs 40+ with if-else)
  • Readable: Clear case-by-case structure
  • Fast: Compiler can optimize to jump table (O(1) lookup!)
  • Maintainable: Easy to add/remove/modify months
  • Type-safe: Expression evaluated once, no repeated checks

Performance comparison (for month = 12):

Approach Comparisons Made Time Complexity
If-Else Chain 12 comparisons O(n) - linear
Switch (unoptimized) 12 comparisons O(n) - but faster constants
Switch (optimized) 1 jump table lookup O(1) - constant!

🚀 Compiler magic: Jump tables!

Modern compilers convert switch statements into jump tables (arrays of function pointers), making lookups instant!

Conceptual jump table:

// Compiler internally creates something like:
void* jumpTable[13] = {
  NULL, // index 0 (unused)
  &january, // index 1
  &february, // index 2
  // ... etc
  &december // index 12
};
// Then just: goto jumpTable[month];

This makes switch incredibly fast for dense integer ranges!

🎨 Code Organization Best Practices

Our formatting style:

case 1:
  cout << "January";
  break;

Alternative valid styles:

Style 1: Compact (one line per case)

case 1: cout << "January"; break;
case 2: cout << "February"; break;

✅ Very compact
✅ Works for simple statements
❌ Can be hard to read with long strings

Style 2: Aligned (our choice)

case 1:
  cout << "January";
  break;
case 2:
  cout << "February";
  break;

✅ Clear visual hierarchy
✅ Easy to scan
✅ Room for multiple statements
✅ Recommended for beginners

Style 3: Braces (for complex cases)

case 1: {
  int days = 31;
  cout << "January has " << days << " days";
  break;
}

✅ Needed for variable declarations
✅ Creates scope for each case
❌ More verbose

Consistency rules:

  • 📏 Pick one style and stick with it throughout your code
  • 📏 Indent consistently (2 or 4 spaces)
  • 📏 Always include break (unless intentional fall-through)
  • 📏 Place default at end (convention)
  • 📏 Add blank line between cases for readability (optional)

Comments for clarity:

switch (month) {
  // Winter months
  case 12: cout << "December"; break;
  case 1: cout << "January"; break;
  case 2: cout << "February"; break;
  
  // Spring months
  case 3: cout << "March"; break;
  // ...
}

🔗 Connecting to Previous Concepts

Building on what you've learned:

From Basic I/O:

  • cin >> month; - Reading integer input
  • cout << "January"; - Printing strings
  • ✅ Data types: long long for large ranges

From Previous Conditionals:

  • ✅ Switch statement basics (Question 12 - Days)
  • ✅ Default case for validation
  • ✅ Break statement importance

New pattern: Scaling up!

Question Cases Range Concept
#12 (Days) 7 + default 0-6 Basic switch
#13 (Months) 12 + default 1-12 Larger switch, 1-based

Combined knowledge example:

// Could combine leap year (Q11) + month (Q13)!
switch (month) {
  case 2:
    if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
      cout << "February has 29 days";
    else
      cout << "February has 28 days";
    break;
  case 1: case 3: case 5: case 7: case 8: case 10: case 12:
    cout << "31 days";
    break;
  default:
    cout << "30 days";
}

🎯 Nested conditionals + switch + leap year logic = powerful combination!

🌍 Real-World Applications

Where month name conversion is used:

1. Date Display in Applications:

// Convert numeric date to readable format
int month = 3, day = 15, year = 2024;
cout << getMonthName(month) << " " << day << ", " << year;
// Output: "March 15, 2024"

2. Calendar Applications:

  • Google Calendar, Outlook
  • Phone calendars
  • Scheduling software

3. Financial Reports:

// Monthly sales report
cout << "Sales for " << getMonthName(currentMonth) << ": $" << sales;

4. Data Validation:

// Check if month is valid before processing
if (month < 1 || month > 12) {
  cout << "Invalid month!";
  return;
}

5. Internationalization (i18n):

// Different languages
switch (month) {
  case 1:
    if (language == "es") cout << "Enero";
    else if (language == "fr") cout << "Janvier";
    else cout << "January";
    break;
}

6. E-commerce:

  • Credit card expiration: "Expires 12/2025" → "December 2025"
  • Subscription billing: "Next payment: March 2024"

7. Logging Systems:

// Log file naming
string logFile = getMonthName(month) + "_" + year + ".log";
// "January_2024.log"

8. Data Analysis:

  • Plotting graphs with month names on X-axis
  • Seasonal analysis (Q1, Q2, etc.)
  • Year-over-year comparisons

💡 Industry Tip: In production code, use date/time libraries (like <chrono> in C++, datetime in Python) instead of manual switch statements. But understanding the logic is crucial!

💡 Key Takeaway: Switch statements scale beautifully from 7 cases to 12, 20, or even 100+ cases! Always use them for discrete value mapping instead of long if-else chains.

Solution

#include <iostream>

using namespace std;

int main() {
    long long month;
    cin >> month;
    
    switch (month) {
        case 1:
            cout << "January";
            break;
        case 2:
            cout << "February";
            break;
        case 3:
            cout << "March";
            break;
        case 4:
            cout << "April";
            break;
        case 5:
            cout << "May";
            break;
        case 6:
            cout << "June";
            break;
        case 7:
            cout << "July";
            break;
        case 8:
            cout << "August";
            break;
        case 9:
            cout << "September";
            break;
        case 10:
            cout << "October";
            break;
        case 11:
            cout << "November";
            break;
        case 12:
            cout << "December";
            break;
        
        default:
            cout << "Invalid";
            break;
    }
    
    return 0;
}