In Learn to Program (2nd Ed) there is an exercise to find leap years between given dates
Write a program that asks for a starting year and an ending year and then puts all the leap years between them (and including them, if they are also leap years). Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). What a mess!
I did some digging and found the 'answer key.' According to the key, the correct code is as follows:
puts 'Input a starting year:'
start_year = gets.chomp
puts 'Input an ending year:'
end_year = gets.chomp
puts ''
while start_year.to_i <= end_year.to_i
if start_year.to_f % 400 == 0
puts start_year
elsif start_year.to_f % 100 == 0
elsif start_year.to_f % 4 == 0
puts start_year
end
start_year = start_year.to_i + 1
end
I was wondering why start_year
needs to be changed to float, and why there are two elsif
statements in a row (% 100
and % 4
) without any instructions for what to do after the one with % 100
.
It seemed from the instructions that operations dealing with 400 and 100 would need to be grouped, but this seems to have operations dealing with 100 and 4 grouped. For example, this code obviously works and doesn't list 1900 as a leap year, but how does it work?
As I'm looking at the code, when the iteration gets to 1900 (say my start and end dates are 1000 and 2000 respectively), it would fail the first if check but then pass both of the elsif
s. So why isn't it part of the output?
Edit
Here is my reformatting of the code. I also made some changes that in my opinion simplified things a bit.
puts 'Input a starting year:'
start_year = gets.chomp.to_i
puts 'Input an ending year:'
end_year = gets.chomp.to_i
puts ''
while start_year <= end_year
if start_year % 400 == 0
puts start_year
elsif start_year % 100 == 0
elsif start_year % 4 == 0
puts start_year
end
start_year = start_year + 1
end