This program displays the number of days in a given month (1-12) using a switch statement, taking leap years into account for February.
C Program
#include <stdio.h>
int main() {
int month, year, days;
printf("Enter month (1-12): ");
scanf("%d", &month);
printf("Enter year: ");
scanf("%d", &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:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
printf("Invalid month.\n");
return 1;
}
printf("Number of days in month %d of year %d: %d\n", month, year, days);
return 0;
}
Explanation
- Grouping
caselabels without abreakbetween them (e.g.case 1: case 3: ...) lets several months share the same 31-day result. - February is handled separately since its day count depends on whether
yearis a leap year. - The leap year rule is: divisible by 4 and not divisible by 100, unless it’s also divisible by 400 (so 2000 is a leap year, but 1900 is not).
- The
defaultcase catches invalid month numbers outside 1-12.
Sample Output
Enter month (1-12): 2
Enter year: 2024
Number of days in month 2 of year 2024: 29
Enter month (1-12): 2
Enter year: 2023
Number of days in month 2 of year 2023: 28