How to write a C Program to Print Number of Days in a Month using Else If statement and Switch Condition with examples?. As we all know, the total number of days in :
- January, March, May, August, October, and December = 31 Days
- April, June, September, and November = 30 Days
- February = 28 or 29 Days
C Program to Print Number of Days in a Month using Else If
This C program will ask the user to enter any number between 1 to 12, where 1 is January, 2 = February, 3 = March,………., and 12 = December.
Based on the user entered integer value, this program will print the number of days in a month. To accomplish this goal, we are using Else If Statement.
/* C Program to Print Number of Days in a Month using Else If Statement */ #include <stdio.h> int main() { int month; printf(" Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : "); scanf("%d", &month); if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { printf("\n 31 Days in this Month"); } else if ( month == 4 || month == 6 || month == 9 || month == 11 ) { printf("\n 30 Days in this Month"); } else if ( month == 2 ) { printf("\n Either 28 or 29 Days in this Month"); } else printf("\n Please enter Valid Number between 1 to 12"); return 0; }
Let me enter the month number as 5
Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : 5
31 Days in this Month
Let me enter the month number as 9
Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : 9
30 Days in this Month
This time, we will enter the wrong value: 15
Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : 15
Please enter Valid Number between 1 to 12
C Program to return Number of Days in a Month using Switch Condition
It is an ideal approach to deal with multiple C Programming conditions. In this program, we are using the Switch Case approach to print the number of days in a month.
#include <stdio.h> int main() { int month; printf(" Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : "); scanf("%d", &month); switch(month ) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: printf("\n 31 Days in this Month"); break; case 4: case 6: case 9: case 11: printf("\n 30 Days in this Month"); break; case 2: printf("\n Either 28 or 29 Days in this Month"); default: printf("\n Please enter Valid Number between 1 to 12"); } return 0; }
Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : 12
31 Days in this Month
Let me try different value
Please Enter the Month Number 1 to 12 (Consider 1 = January, and 12 = December) : 6
30 Days in this Month