This blog is under construction

Monday 8 July 2013

C program to check whether a date is valid or not

Write a C program to check whether a date is valid or not.


  #include <stdio.h>
  #include <string.h>
  #define YEAR 2013
  #define MONTH 12
  int main() {
        int day, month, year, flag = 0;
        int daysInMonth[12] = {31, 28, 31, 30, 31, 30,
                               31, 31, 30, 31, 30, 31};
        char str[100];

        /* get the input date from the user */
        printf("Enter your input date(DD/MM/YYYY):");
        fgets(str, 100, stdin);
        str[strlen(str) - 1] = '\0';

        /* i/p day, month and year from the above string from user */
        sscanf(str, "%d/%d/%d", &day, &month, &year);

        /* year should not be greater than current year */
        if (year > YEAR || year <= 0) {
                printf("Invalid Date!!\n");
                return 0;
        }

        /* only 12 months in a year */
        if (month > MONTH || month <= 0) {
                printf("Invalid Date!!\n");
                return 0;
        }

        /* leap year check if month is february */
        if (month == 2) {
                if (year % 100 == 0) {
                        if (year % 400 == 0) {
                                flag = 1;
                        }
                } else if (year % 4 == 0) {
                        flag = 1;
                }
                if (day > (daysInMonth[month - 1] + flag)) {
                        printf("Invalid Date !!\n");
                        return 0;
                }
        }

        /* check whethe day is valid or not */
        if (day > daysInMonth[month - 1]) {
                printf("Invalid Date!!\n");
                return 0;
        }

        /* print the result */
        printf("Valid Date!!\n");
        return 0;

  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input date(DD/MM/YYYY):31/02/2001
  Invalid Date !!






See Also:

1 comment:

  1. This code can get a bug at leap year.

    On Feb, we've already done invalid day checking. You'd to add "else if (...)" statement below Feb checking.

    If we change to code below, we can fix this issue.

    /* leap year check if month is february */
    if (month == 2)
    {
    if (year % 100 == 0)
    {
    if (year % 400 == 0)
    {
    flag = 1;
    }
    }
    else if (year % 4 == 0)
    {
    flag = 1;
    }

    if (day > (daysInMonth[month - 1] + flag))
    {
    printf("3.Invalid Date !!\n");
    return -1;
    }
    }
    else if (day > daysInMonth[month - 1]) /* check whethe day is valid or not */
    {
    printf("4.Invalid Date!!\n");
    return -1;
    }

    Best Regard,

    ReplyDelete