Search code examples
cif-statementnested-ifleap-yearrelational-operators

A leap year determining C program is not giving any output when inputting 2000, 1900 or 2100 as an input


When I am running this C program, and giving 2020, 2024 or other years perfectly divisible by 4, then I am getting expected output i.e. it is a leap year. But when I am giving a century year : 1900, 2000 or 2100 etc. as an input, then it's not not giving me any output.

Please do not suggest me the correct program as there are many available on internet and I understood them already. You are requested to tell me why my program is not giving any output when entering a century year.

P.S. this program gives no error.

Program:

#include <stdio.h>

int main()
{
    int n;
    printf("Enter year : "); scanf("%d",&n);
    
    if (n%4==0)
    {
        if(n%100 != 0)
        {
            printf("Leap year"); 
        }
    }
    else if(n%100 == 0)
    {
        if (n%400==0)
        {
            //`enter code here`
            printf("Leap year");
        }
    }
    else 
        printf("Not a Leap year");

    return 0;
}

Solution

  • There is a problem in this part of the code:

    if (n%4==0)
    {
        if(n%100 != 0)
        {
            printf("Leap year"); 
        }
    }
    

    When you enter 1900, it enters the first condition. (Because 1900%4 is equal to zero.) And then, it checks whether or not 1900%100 is zero, and as you can see, it is zero, so it doesn't enter the if(n%100!=0) condition, and there is no other else statement in the if (n%4==0). So there is no condition for the code to enter. And therefore it doesn't give any output. Plus your code never enters else if(n%100 == 0) part because any number that is divisible by 100 is also divisible by 4.