C program to print number of days in a month using switch case

Write a C program to enter month number and print total number of days in month using switch case. C program to find total number of days in a month.
Also view this program using if else - C program to print number of days in a month using if else.

Example:
Input month number: 3
Output: Total number of days = 31

Required knowledge:

Basic programming, Switch case

Number of days in each month

Month Total days
January 31 days
February 28/29 days
March 31 days
April 30 days
May 31 days
June 30 days
July 31 days
August 31 days
September 30 days
October 31 days
November 30 days
December 31 days


Program:

/**
 * C program to print number of days in a month using switch case 
 */

#include <stdio.h>

int main()
{
    int month;

    /*
     * Reads 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;
} 

Note: The above program can be also re-written in short as
/**
 * C program to print number of days in a month using switch case
 */

#include <stdio.h>

int main()
{
    int month;

    /*
     * Reads month number from user
     */
    printf("Enter month number(1-12): ");
    scanf("%d", &month);

    switch(month)
    {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12: printf("31 days");
            break;
        case 4:
        case 6:
        case 9:
        case 11: printf("30 days");
            break;
        case 2: printf("28/29 days");
            break;
        default: printf("Invalid input! Please enter month number between 1-12");

    }
    return 0;
} 
Note: In the above program for any case in 1, 3, 5, 7, 8, 10, 12 the output will be 31 days. And for any case 4, 6, 9, 11 output will be 30 days.

Output
X
_
Enter month number(1-12): 3

31 days

Happy coding ;)

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment