C PROGRAMMING PROGRAM • SWITCH & MENU PROGRAMS

Find the Number of Days in a Month Using switch

Learn how to find the number of days in a month using switch using a clear C program.

BeginnerswitchGrouped casesLeap year

PROBLEM UNDERSTANDING

Input and expected output

Sample input
2 2028
Sample output
Days = 29

COMPLETE C PROGRAM

Complete C implementation

switch-month-days.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int month, year, days;
    printf("Enter month number and year: ");
    scanf("%d %d", &month, &year);
    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 = (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) ? 29 : 28;
            break;
        default: puts("Invalid month number."); return 0;
    }
    printf("Days = %d\n", days);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Days = 29
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Group months with equal lengths in shared cases and calculate February from the leap-year rule.
  3. Display the computed result.

Group months with equal lengths in shared cases and calculate February from the leap-year rule.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.