Example
Input
Enter month number: 1
Output
It contains 31 days.
Logic to find number of days in a month
Total days in a months 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 find number of days in given month.
- Input month number from user. Store it in some variable say month.
- For each month check separately and print corresponding number of days in that month using above table. For example, print 31 days if
month == 1
since, January contains 31 days. - Repeat the above step for all 12 months.
/**
* C program to print number of days in a month
*/
#include <stdio.h>
int main()
{
int month;
/* Input month number from user */
printf("Enter month number (1-12): ");
scanf("%d", &month);
if(month == 1)
{
printf("31 days");
}
else if(month == 2)
{
printf("28 or 29 days");
}
else if(month == 3)
{
printf("31 days");
}
else if(month == 4)
{
printf("30 days");
}
else if(month == 5)
{
printf("31 days");
}
else if(month == 6)
{
printf("30 days");
}
else if(month == 7)
{
printf("31 days");
}
else if(month == 8)
{
printf("31 days");
}
else if(month == 9)
{
printf("30 days");
}
else if(month == 10)
{
printf("31 days");
}
else if(month == 11)
{
printf("30 days");
}
else if(month == 12)
{
printf("31 days");
}
else
{
printf("Invalid input! Please enter month number between (1-12).");
}
return 0;
}
/*
Output :
Enter month number (1-12): 12
31 days
*/
Program to print days in a month using logical OR operator
/**
* C program to print number of days in a month using logical operator
*/
#include <stdio.h>
int main()
{
int month;
/* Input month number from user */
printf("Enter month number (1-12): ");
scanf("%d", &month);
/* Group all 31 days conditions together using logical OR operator */
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
{
printf("31 days");
}
else if(month==4 || month==6 || month==9 || month==11)
{
/* Group all 30 days months together */
printf("30 days");
}
else if(month==2)
{
printf("28 or 29 days");
}
else
{
printf("Invalid input! Please enter month number between (1-12).");
}
return 0;
}
/*
Output :
Enter month number (1-12): 12
31 days
*/
Program to print days in a month using array
/**
* C program to print number of days in a month using array
*/
#include <stdio.h>
int main()
{
/* Constant number of month declarations */
const int MONTHS[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int month;
/* Input month number from user */
printf("Enter month number (1-12): ");
scanf("%d", &month);
if(month >= 1 && month <= 12)
{
/* Print number of days */
printf("%d days", MONTHS[month - 1]);
}
else
{
printf("Invalid input! Please enter month number between (1-12).");
}
return 0;
}
/*
Output :
Enter month number (1-12): 12
31 days
*/