Pages - Menu

Monday 8 October 2012

Leap year checking algorithm in C

A leap year (or intercalary or bissextile year) is a year containing one aditional day in order to keep the calendar year synchronised with the astronomical or seasonal year. 

For example, in the Gregorian calendar, February in a leap year has 29 days instead of 28, so the year lasts 366 days instead of 365. (wikipedia)

The C function below checks if the year received as argument in the function call is a leap year or not.
/*
 * Description:
 *  Checks if a year is a leap year of not
 * Parameters:
 *  year - year to be evaluated
 * Returns:
 *  0 - the year is not a leap year
 *  1 - the year is a leap year
 */
int LeapYear(int year)
{
    int isLeapYear = -1;
    if(year%400 == 0)
    {
        isLeapYear = 1;
    }
    else if(year%100 == 0)
    {
        isLeapYear = 0;
    }
    else if(year%4 == 0)
    {
        isLeapYear = 1;
    }
    else
    {
        isLeapYear = 0;
    }
    return isLeapYear;
}

Example: 

This C program reads a year from the keyboard and, using the function defined above, checks whether or not the year entered is a leap year or not.

#include<stdio.h>
#include<conio.h>

int main(void)
{
    int year = 0, isLeapYear = -1;
    printf("\n Enter the year: ");
    scanf("%d",&year);
    isLeapYear = LeapYear(year);
    if (isLeapYear == 1)
    {
        printf("\n\t%d is a leap year.",year);
    }
    else if(isLeapYear == 0)
    {
        printf("\n\t%d is not a leap year.",year);
    }
    getch();
    return 0;
}
Output:   

No comments:

Post a Comment