C program to check if a year is leap year or not

C program to check if a year is leap year or not :

To check if a year is leap year or not, we need to check if it is divisible by 4 or not. A year is leap year if it is divisible by 4 and for century years, if it also divisible by 400. In this example, we will learn how to check if a year is leap year or not in C programming language. Let’s take a look into the algorithm first :

Algorithm to check if a year is leap year or not :

1. Check if it is divisible by 4. If not than it is not a leap year.
2. If divisible by 4, check if it is divisible by 100. If not , it is not a century year, so it is a leap year.
3. If divisible by 100, check if it is divisible by 400 or not. If yes it is a leap year, else not.

List of leap years from 1900 to 2020 are : 1904, 1908, 1912, 1916, 1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020 .
Let’s take a look into the program :

#include
#define LEAP_YEAR 1
#define NON_LEAP_YEAR 0


int checkLeapYear(int year){
    if(year%4 == 0 ){
        if(year%100 == 0){
            if(year%400 == 0){
                return LEAP_YEAR;
            }else{
                return NON_LEAP_YEAR;
            }
        }else{
            return LEAP_YEAR;
        }
    }else{
        return NON_LEAP_YEAR;
    }
}


int main()
{
    int year;

    printf("Enter a year to check : \n");

    scanf("%d",&year);

    if(checkLeapYear(year) == LEAP_YEAR){
        printf("Entered year is a leap year.");
    }else{
        printf("Entered year is not a leap year.");
    }

    return 0;
}

We can also simplify the checkLeapYear function as below :

#include
#define LEAP_YEAR 1
#define NON_LEAP_YEAR 0


int checkLeapYear(int year)
{
  if(((year%4==0) && (year%100!=0)) ||(year%400==0)){
    return LEAP_YEAR;
  }else{
    return NON_LEAP_YEAR;
  }
}
int main()
{
    int year;

    printf("Enter a year to check : \n");

    scanf("%d",&year);

    if(checkLeapYear(year) == LEAP_YEAR){
        printf("Entered year is a leap year.");
    }else{
        printf("Entered year is not a leap year.");
    }

    return 0;
}

Sample Output :

Enter a year to check :
2018
Entered year is not a leap year.

Enter a year to check :
1984
Entered year is a leap year.

Enter a year to check :
2000
Entered year is a leap year.

The output is same for both of these program.

Leave a Reply