Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A year is a leap year when it divides exactly by 4, except that a year dividing by 100 is a leap year only if it also divides by 400. This program counts leap years.
FUNCTION IsLeap(Year : INTEGER) RETURNS BOOLEAN
IF MOD(Year, 400) = 0
THEN
RETURN TRUE
ENDIF
IF MOD(Year, 100) = 0
THEN
RETURN FALSE
ENDIF
RETURN MOD(Year, 4) = 0
ENDFUNCTION
DECLARE Year : INTEGER
DECLARE Leaps : INTEGER
Leaps ← 0
FOR Year ← 1990 TO 2030
IF IsLeap(Year)
THEN
Leaps ← Leaps + 1
ENDIF
NEXT Year
OUTPUT LeapsWhat does IsLeap return for 1900, 2000 and 2024? What is output?
DIV is the whole part of a division and MOD the remainder. ROUND(Value, Places) rounds to a number of decimal places, and RANDOM() returns a number from 0 to 1. LENGTH(Text) counts the characters, SUBSTRING(Text, Start, Length) takes a piece starting at Start (position 1 is the first character), UCASE and LCASE change the case.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. Three test years.
IsLeap returns FALSE.MOD(2024, 4) = 0, so it returns TRUE.Step 2. The count. The years from 1990 to 2030 that divide by 4 are 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024 and 2028. The only century year, 2000, is a leap year. The output is 10.
Watch out. The order of the tests matters. Testing MOD(Year, 4) first would call 1900 a leap year.
Answer: FALSE, TRUE, TRUE, and the output is 10.
Log in to join the discussion.
Loading…