Tuesday, December 14, 2010

Test Question 1 Review 6 - Loops: what not to do

I noticed in the test some people were using a Do While (condition) with a strange condition. It's actually a bit of a worry


prompt user: "please enter a start year for the leap year range calculator"
(get startYear from the user)
prompt user: "please enter an end year for the leap year range calculator"
(get endYear from the user)
Do while (startYear <> endYear)
COMMENT: leap year logic goes here
startYear = startYear + 1
end loop


It's the startYear <> endYear part that is a concern.

Because it is a range of years it will be increasing by one every loop iteration. Yes, that's what is happening in the above pseudocode. But with the startYear "not equals to" endYear (instead looping until it no longer is "less than or equals to"), you run the risk of the loop never ending.

Imagine the test data of startYear being 1894 and endYear of 1795.

Do while (1894 <> 1795)
COMMENT: leap year logic goes here
startYear = startYear + 1
end loop

The loop will start because the condition will let it (1894 does not equal 1795) but 1894 will increase by one every time the loop is run and will never reach 1795

If you try that with "less than or equal to" (instead of "not equal to") then it won't enter the loop at all (condition not met for the first time)

Do while (1894 <= 1795)
COMMENT: leap year logic goes here
startYear = startYear + 1
end loop

which may (or may not) be acceptable (depending on the spec: the test question didn't mention anything about handling endYear being less than startYear)

REVISON WORK

Take the working code from
http://pseudocodehelp.blogspot.com/2010/12/test-question-1-review-5-final-vbnet.html
and modify the FOR NEXT loop to be a DO WHILE loop. Then change the conditions to the two different versions I have talked about here. Try it with lots of test data and see what you get. Look for "Edge cases" and try to break it (why try to break it? Because your users will try).

Post your results over on the
http://groups.google.com/group/pseudocodehelp
discussion group.