Check a Leap Year
Leap-year rules are a useful exercise in combining boolean conditions.
What is Check a Leap Year?
Leap-year rules are a useful exercise in combining boolean conditions.
Determine whether a year is a leap year.
Important points
- Compile with warnings enabled and fix every warning.
- Know the lifetime and type of every value.
- Validate input and keep array bounds explicit.
C and C++ code examples
main.c
#include <stdio.h>
int main(void) {
int year = 2024;
// Apply the Gregorian calendar rules in one expression.
int leap = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
printf("%d is %sa leap year\n", year, leap ? "" : "not ");
}
2024 is a leap year
C++
main.cpp
#include <iostream>
int main() {
int year = 2024;
// Apply the Gregorian calendar rules in one expression.
bool leap = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
std::cout << year << " is " << (leap ? "" : "not ") << "a leap year\n";
}
2024 is a leap year
C and C++ comparison
Years divisible by 400 are leap years; other century years are not; remaining years must be divisible by four.
C
C exposes small procedural APIs and makes representation details explicit.
C++
C++ retains the low-level model while adding safer library types and abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add invalid and boundary-value inputs.
- Compile with -Wall -Wextra -Wpedantic.
- Move reusable declarations into a header and implementation file.