Example
Input
Input month number: 3
Output
Total number of days = 31
Logic to print number of days in month using switch...case
Total days in a month is given by below table.
Month | Total days |
---|---|
January, March, May, July, August, October, December | 31 days |
February | 28/29 days |
April, June, September, November | 30 days |
Step by step descriptive logic to print number of days in a month using switch...case
.
- Input month number from user. Store it in some variable say month.
- Switch the value of month i.e.
switch(month)
and match with cases. - There can be 12 possible values (choices) of month i.e. from 1 to 12. Hence, write 12 cases inside
switch
and onedefault
case aselse
block. - Print 31 for case 1, 3, 5, 7, 8, 10, 12.
- Print 30 for case 4, 6, 9, 11.
- Print 28/29 for case 2.
- Print invalid input for
default
case.
/**
* C program to print number of days in a month using switch case
*/
#include <stdio.h>
int main()
{
int month;
/* Input month number from user */
printf("Enter month number(1-12): ");
scanf("%d", &month);
switch(month)
{
case 1:
printf("31 days");
break;
case 2:
printf("28/29 days");
break;
case 3:
printf("31 days");
break;
case 4:
printf("30 days");
break;
case 5:
printf("31 days");
break;
case 6:
printf("30 days");
break;
case 7:
printf("31 days");
break;
case 8:
printf("31 days");
break;
case 9:
printf("30 days");
break;
case 10:
printf("31 days");
break;
case 11:
printf("30 days");
break;
case 12:
printf("31 days");
break;
default:
printf("Invalid input! Please enter month number between 1-12");
}
return 0;
}
/*
Output :
Enter month number(1-12): 3
31 days
*/
best approach
/**
* C program to print number of days in a month using switch case
*/
#include <stdio.h>
int main()
{
int month;
/* Input month number from user */
printf("Enter month number(1-12): ");
scanf("%d", &month);
switch(month)
{
/* Group all 31 days cases together */
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
printf("31 days");
break;
/* Group all 30 days cases together */
case 4:
case 6:
case 9:
case 11:
printf("30 days");
break;
/* Remaining case */
case 2:
printf("28/29 days");
break;
default:
printf("Invalid input! Please enter month number between 1-12");
}
return 0;
}
/*
Output :
Enter month number(1-12): 3
31 days
*/