cif-statementleap-yearlogical-orlogical-and

Use of logical operators in Leap year problem


I am quite new in this programming world and my question may sound silly but can anyone explain difference between following 2 codes.

Code 1

    int yr;
    printf("enter the respective year=\n");
    scanf("%d", &yr);
    if(yr%400==0 || yr%100!=0 && yr%4==0)
        printf("It is a leap year\n");
    else
        printf("It is not a leap year\n");

    return 0;

Code 2

    int yr;
    printf("enter the respective year=\n");
    scanf("%d", &yr);
    if((yr%100==0 && yr%400==0) || yr%4==0)
        printf("It is a leap year\n");
    else
        printf("It is not a leap year\n");

    return 0;

I think both should work well but when I executed them then only Code 1 is giving right answers.


Solution

  • The condition in the if statement

    if(yr%400==0 || yr%100!=0 && yr%4==0)
    

    that can be equivalently rewritten using parentheses like

    if ( ( yr%400==0 ) || ( yr%100!=0 && yr%4==0 ) )
    

    means that a leap year is the year that either divisible by 400 or divisible by 4 and at the same time is not divisible by 100.

    For example the year 1900 is not a leap year because it is not divisible by 400 and on the other hand is divisible by 100.

    The condition in this if statement

    if((yr%100==0 && yr%400==0) || yr%4==0)
    

    means that any year divisible by 4 is a leap year due to the second sub-expression yr%4==0 that always yields logical true for any year divisible by 4. So it is even unimportant what will be the logical result of the first sub-expression (yr%100==0 && yr%400==0) because any number divisible by 100 and 400 is divisible at the same time by 4.

    So the second if statement is logically wrong. It accepts the year 1900 as a leap year.