Basics · beginner
C Program to Check Leap Year
Check whether a year is a leap year in C with the full rule (divisible by 4, but centuries only when divisible by 400) in a function that returns a bool.
- modulus %
- && and ||
- functions
- stdbool.h
A leap year has 366 days. A year divisible by 4 is a leap year, except years divisible by 100, which are not, except years divisible by 400, which are. 2024 and 2000 are leap years; 1900 and 2100 are not.
The rule fits in one boolean expression. Putting it in a function returning bool (from stdbool.h) makes the program read like the rule.
The program
#include <stdbool.h>
#include <stdio.h>
bool is_leap(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
int main(void) {
int years[] = {2024, 2023, 1900, 2000};
for (int i = 0; i < 4; i++) {
printf("%d %s\n", years[i], is_leap(years[i]) ? "is a leap year" : "is not a leap year");
}
return 0;
}2024 is a leap year
2023 is not a leap year
1900 is not a leap year
2000 is a leap yearHow it works
- year % 4 == 0 keeps only years divisible by 4.
- The bracketed part accepts years that are not centuries, or centuries divisible by 400.
- && needs both parts, so 1900 is rejected and 2000 accepted.
- stdbool.h provides bool, true and false; the conditional operator picks the sentence to print.
Another way: Nested if statements
The same rule as three nested decisions, which some textbooks prefer because each line matches one part of the rule.
#include <stdio.h>
int main(void) {
int year = 1900;
if (year % 400 == 0)
printf("%d is a leap year\n", year);
else if (year % 100 == 0)
printf("%d is not a leap year\n", year);
else if (year % 4 == 0)
printf("%d is a leap year\n", year);
else
printf("%d is not a leap year\n", year);
return 0;
}1900 is not a leap yearCommon mistakes
- Checking only year % 4 == 0, which makes 1900 a leap year.
- Dropping the brackets: && binds tighter than ||, so the meaning changes.
- Testing the conditions in the wrong order in nested ifs (checking % 4 before % 100), which accepts 1900.
Try it yourself
- Print all leap years between 1890 and 1920.
- Write days_in_month(month, year) that uses is_leap for February.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.