Check Leap Year in C

Exercise:

Write a C Program to check leap year.

Click Here to View the Solution!
#include <stdio.h>       
int main() {
    int year;
    printf("Enter a year: ");
    scanf("%d", &year);

    // leap year if perfectly divisible by 400
    if (year % 400 == 0) {
        printf("%d is a leap year.", year);
    }

    // not a leap year if divisible by 100
    else if (year % 100 == 0) {
        printf("%d is not a leap year.", year);
    }

    // leap year if not divisible by 100 but divisible by 4
    else if (year % 4 == 0) {
        printf("%d is a leap year.", year);
    }

    // all other years are not leap year
    else {
        printf("%d is not a leap year.", year);
   }
   return 0;
}
Click Here to View the Output!
Enter a year: 2016 
2016 is a leap year. 
Click Here to View the Explanation!
  • This program is used to determine whether a year is a leap year.
  • In the main method, the program requests the user to enter a year and store in an integer variable year using the scanf() function.
  • The program uses multiple if…else if statements. Initially, the program checks whether the entered year is exactly divisible by 400 i.e. year % 400 = 0. If true, the year will be a leap year and a message will be printed.
  • The program then checks whether the year is exactly divisible by 100 when not divisible by 400. If true, the year will not be a leap year and a message will be printed.
  • If the year is not divisible by 100, the program checks whether the year is exactly divisible by 4. If true, the year will be a leap year and a message will be printed.
  • If neither of the if…else if statements are true, the else statement will be executed which prints that year is not a leap year. Since, every year besides the previously stated conditions is not a leap year.
  • The return 0 statement is used to exit the program execution.