In this blog post, we learn how to write a C program to find number of days in a month?. We will write the C program to find number of days in a month. Write a C program to input the month from the user and find the number of days. How to find a number of days in a given month in C programming. Logic to find the number of days for a given month.
Example,
Input: 3 Output: 31 days Input: 12 Output: 31 days
Step by step descriptive logic to find number of days in given month and year:
- Get input month and year from the user and store it in some variable. Here I am using two variable months and years to store the value.
- Check the leap year for Feb month because Feb month could have 28 or 29 days (for leap year).
- Now use the below table to find the number of days in the given month and year.
Month | Total days |
---|---|
January, March, May, July, August, October, December | 31 days |
February | 28/29 days |
April, June, September, November | 30 days |
C program to find number of days in a month using switch case:
The below program ask the user to enter the valid month and year. After getting the value of a month and year from the user program display the number of days using the switch case. We have used the above-mentioned table to find the number of days.
#include<stdio.h> enum MonthIndex { Jan = 1, Feb = 2, Mar = 3, Apr = 4, May = 5, Jun = 6, Jul = 7, Aug = 8, Sep = 9, Oct = 10, Nov = 11, Dec = 12 }; int isLeapYear(unsigned int year) { return ((year%400 == 0) || ((year%4 == 0) && (year%100!=0))); } unsigned char findDaysInMonth(unsigned int const year, unsigned char const month) { unsigned char numberOfDays; switch (month) { case Jan: case Mar: case May: case Jul: case Aug: case Oct: case Dec: numberOfDays = 31; break; case Apr: case Jun: case Sep: case Nov: numberOfDays = 30; break; case Feb: if (isLeapYear (year)) { numberOfDays = 29; } else { numberOfDays = 28; } break; default: numberOfDays = 0; break; } return numberOfDays; } int main() { int month, year; unsigned char numberOfDays; //Ask user to input year (+ve) printf("Enter year: "); scanf("%u", &year); //Ask user to input month between 1 to 12 printf("Enter month number(1-12): "); scanf("%d", &month); numberOfDays = findDaysInMonth(year, month); if(numberOfDays!= 0) { printf("Days number = %d",numberOfDays); } else { printf("Please enter valid input"); } return 0; }
Output:
Recommended Articles for you:
- How to use if in C programming.
- How to use C if-else condition?
- C program to print number of days in a month
- Check leap year using C program
- Using the C program to check valid date (date is valid or not)
- Check expiry date Using C program
- C program to print day name of week
- Convert number of days in terms of Years, Weeks and Days using C program
- C program to find century for a year
- Create an employee record system in C.
- Way to create a library management system in C.
- How to create student record system in C?