I made a program using C to find whether the entered year is a leap year or not. But unfortunately its not working well. It says a year is leap and the preceding year is not leap.
#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
int year;
printf("Enter a year:");
scanf("%d",&year);
if(!yearr(year))
{
printf("It is a leap year.");
}
else
{
printf("It is not a leap year");
}
getch();
}
int yearr(int year)
{
if((year%4==0)&&(year/4!=0))
return 1;
else
return 0;
}
After reading the comments i edited my coding as:
#include<stdio.h>
#include<conio.h>
int yearr(int year);
void main(void)
{
int year;
printf("Enter a year:");
scanf("%d",&year);
if(!yearr(year))
{
printf("It is a leap year.");
}
else
{
printf("It is not a leap year");
}
getch();
}
int yearr(int year)
{
if((year%4==0)
{
if(year%400==0)
return 1;
if(year%100==0)
return 0;
}
else
return 0;
}
From Wikipedia article on Leap year:
Although the logic that divides by 400 first is impeccable, it is not as computationally efficient as dividing by 4 first. You can do that with the logic:
This divides by 4 for every value, but for 3/4 of them, the testing terminates there. For the 1/4 that pass the first test, it then divides by 100, eliminating 24/25 values; for the remaining 1 out of a 100, it divides by 400 too, coming up with a final answer. Granted, this is not a huge saving.
The problem with your code is that you are returning a non-zero value from
yearr
if you think that the year is a leap year. So you don't need the!
in your if statement.