Wednesday, June 28, 2006

LeapYear Assignment

Program:

# LeapYear.rb - This program reads an year and tells whether it is a LeapYear or not.
# Author - Ashish Kulkarni (http://ashishkulkarni.blogspot.com)
# Date - 28-Jun-2006

puts 'Please input the year for checking for Leap Year:'
STDOUT.flush
year = STDIN.gets.chomp.to_i

if year.modulo(4) == 0
if year.modulo(100) == 0
if year.modulo(400) == 0
puts 'It is a Leap Year'
else
puts 'It is not a Leap Year'
end
else
puts 'It is a Leap Year'
end
else
puts 'It is not a Leap Year'
end

Output:

Please input the year for checking for Leap Year:
2000
It is a Leap Year

Please input the year for checking for Leap Year:
2001
It is not a Leap Year

Please input the year for checking for Leap Year:
2003
It is not a Leap Year

Please input the year for checking for Leap Year:
2004
It is a Leap Year

Please input the year for checking for Leap Year:
2008
It is a Leap Year

Please input the year for checking for Leap Year:
3000
It is not a Leap Year

I made use of the Ruby Manual under C:\ruby\doc\ProgrammingRuby.chm to find the modulo() function.

2 Comments:

At 11:52 am, Blogger SatishTalim said...

Can you use the || and && operators to shorten the code?

 
At 4:12 pm, Blogger Ashish Kulkarni said...

Here is the version 2.0 of the program:

# LeapYearv2.rb - This program reads an year and tells whether it is a LeapYear or not.
# Author - Ashish Kulkarni (http://ashishkulkarni.blogspot.com)
# Date - 28-Jun-2006

GregorianCutoverYear = 1582

puts 'Please input the year for checking for Leap Year:'
STDOUT.flush
year = STDIN.gets.chomp.to_i

if (year >= GregorianCutoverYear && # Gregorian
((year.modulo(4) == 0) &&
((year.modulo(100) != 0) ||
(year.modulo(400) == 0)))) ||
(year < GregorianCutoverYear && # Julian
year.modulo(4) == 0)
puts 'It is a Leap Year'
else
puts 'It is not a Leap Year'
end


Output:

Please input the year for checking for Leap Year:
2000
It is a Leap Year

Please input the year for checking for Leap Year:
2002
It is not a Leap Year

Please input the year for checking for Leap Year:
2004
It is a Leap Year

Please input the year for checking for Leap Year:
2006
It is not a Leap Year

Please input the year for checking for Leap Year:
3000
It is not a Leap Year

 

Post a Comment

<< Home