C program to find number of days in a month :
This post will show you how to find the number of days in a month in C programming language. We will use switch case to solve this problem.
Following are the steps of this program:
- Take the month as input from the user
- Print the days for the month and print it out
C program:
Below is the complete C program :
#include<stdio.h>
int getDays(int month){
switch(month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return -1;
}
}
int main(){
int month;
printf("Enter month in number :");
scanf("%d",&month);
printf("Total days : %d\n",getDays(month));
}
Explanation:
In this program:
- We are taking the month as input from the user and storing it in the variable month.
- getDays method is used to get the number of days for the month entered. Month should be entered in number e.g. 1 for January, 2 for February etc.
- Inside the switch block, we are combining cases . For example, for 1,3,5,7,8,10,12 month, we have 31 days and for other months we have 30 days. So, we are clubbing them together.
Sample Output:
Enter month in number :3
31
Enter month in number :9
Total days : 30