A Problem Solved: Leap Years
In this lesson, we will use if statements to see whether a given year is a leap year.
We'll cover the following
Problem statement
Is this year a leap year? Will the year 3000 be a leap year? Let’s write a program to find out.
Pseudocode
The overall logic of the program is not complicated, as you can see from the following pseudocode:
Describe the program’s purpose
Ask the user to type a year
Read the year
Test whether the year is a leap year
Display the results
Let’s tackle the hardest part—testing whether a year is a leap year. A year is a leap year if it is:
- Divisible by 4 but not divisible by 100
or - Divisible by 400
For example, the years 2000 and 2008 were leap years, but 2099 and 3000 will not be.
We need to translate the criteria for a leap year into Java. If year
is an int
variable containing the year, we can list each of the necessary tests in English and its Java equivalent, as follows:
- Divisible by 4
year % 4 == 0
- Not divisible by 100
year % 100 != 0
- Divisible by 400
year % 400 == 0
For the year to be divisible by 4
, the remainder after dividing the year by 4
must be 0. This will be the case if the expression year % 4
is 0
, that is, if the expression year % 4 == 0
is true. Similarly, a year is not divisible by 100
if the remainder after dividing the year by 100
is not 0
. In that case, the expression year % 100 != 0
is true. Both of these criteria must be true simultaneously to satisfy the
requirement “Divisible by 4 but not divisible by 100.” That is, a year is a leap year if the expression, (year % 4 == 0) && (year % 100 != 0)
is true.
If this expression is false, the year can still be a leap year if it is divisible by 400—that is, if year % 400 == 0
is true. By combining these observations, we see that a year is a leap year if the expression,
( (year % 4 == 0) && (year % 100 != 0) ) || (year % 400 == 0)
is true.
Program
You can see this expression used in the following leap-year program.
Get hands-on with 1200+ tech skills courses.