C program to enter month number and print number of days in month

Write a C program to enter month number between(1-12) and print the number of days in month using if else. How to print total number of days in a given month using if else in C programming. Program to enter month number from user and find number of days in month using if else in C.

Example:
Input month number: 1
Output: 31 days

Required knowledge

Basic C programming, If else

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 to print number of days in month

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

#include <stdio.h>

int main()
{
    int month;

    /* Read 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).\n");
    }

    return 0;
}


Note: This program can also be written in short using logical OR || operator.


Program to print days in a month using OR operator

/**
 * C program to print number of days in a month using logical operator
 */

#include <stdio.h>

int main()
{
    int month;

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


    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)
    {
        printf("30 days");
    }
    else if(month==2)
    {
        printf("28 or 29 days");
    }
    else
    {
        printf("Invalid input! Please enter month number between (1-12).\n");
    }

    return 0;
} 


Output
Enter month number (1-12): 1
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