Search code examples
cdatelogic

A C program to check if the entered date is valid or not


I was asked to right a program which checks if the date entered by the user is legitimate or not in C. I tried writing it but I guess the logic isn't right.

//Legitimate date
#include <stdio.h>
void main()
{
    int d,m,y,leap;
    int legit = 0;
    printf("Enter the date\n");
    scanf("%i.%i.%i",&d,&m,&y);
    if(y % 400 == 0 || (y % 100 != 0 && y % 4 == 0))
        {leap=1;}
    if (m<13)
    {
        if (m == 1 || (3 || ( 5 || ( 7 || ( 8 || ( 10 || ( 12 )))))))
            {if (d <=31)
                {legit=1;}}
        else if (m == 4 || ( 6 || ( 9 || ( 11 ) ) ) )
            {if (d <= 30)
                {legit = 1;}}
        else
            {
                        if (leap == 1)
                              {if (d <= 29)
                                    {legit = 1;}}
                        if (leap == 0)
                              {{if (d <= 28)
                                    legit = 1;}}
             }
    }
    if (legit==1)
        printf("It is a legitimate date!\n");
    else
        printf("It's not a legitimate date!");

}

I am getting the correct output if the month has 31 days but for the rest of the months, the output is legitimate if the day is less than 32. Your help is appreciated!


Solution

  • You can't chain conditionals like this:

    if (m == 1 || (3 || ( 5 || ( 7 || ( 8 || ( 10 || ( 12 )))))))
    

    Instead, you'll have to test each scenario specially:

    if (m == 1 || m == 3 || m == 5 || ...)
    

    Your version simply ORs the results of the first test (m == 1) with the value of 3, which in C is a non-zero and therefore always a boolean true.