From: Robert Klemme Date: 2007-09-02T00:00:04+09:00 Subject: Re: Help with leap year programing On 01.09.2007 16:33, HB wrote: > I am a beginner on programming now reading books by Chris Pine: Learn > to Program. > On chapter 6, I got same assignment. I guess that is a classic one. > > I have tried to use what I have learned so far: The loop. > > My code is as below. i have run several test without finding any > problem. > > Can you help to have a look and throw some light on any possible > improvement? Thanks. The fist thing I'd change is to remove all the #to_i's. You should convert to integer just once, namely after reading user input. If you use Integer() for the conversion, then you also get automatic error checking, i.e., if the user enters "foo" no calculations will be done but he will see an error message instead. Next, I am not sure what you are trying to achieve. As far as I can see there is no condition on the "puts s" but your print statement seems to indicate that you are interested in leap years only. If you want to print leap years only then you need to somehow put a condition around that output statement. Normally you would need just a single loop as far as I understand the problem and what you are trying to do. So you could get rid of one of them. I would also move the leap year output code inside the if-else. The code will likely work the way it is as well because if s>e the body of the while loop will never be executed. But from a control flow point of view the code becomes clearer when you nest the "activity" (leap year calculation and output in this case) in the proper branch of the conditional statement. > ____________________ > > puts 'starting year:' > s = gets.chop > puts 'ending year:' > e = gets.chop > > if s.to_i > e.to_i > puts 'ending year should be bigger than staring year' > else > puts 'leap year between ' + s + ' and '+ e + ' as below:' > end > > while s.to_i < e.to_i > > while ( (s.to_i % 4 == 0 and s.to_i % 100 != 0) or (s.to_i % 100 == > 0 and s.to_i % 400 == 0 )) > puts s > s = s.to_i + 1 > end > s = s.to_i + 1 > end > puts 'all done' Kind regards robert