Friday, 18 November 2016

"Do while" annoyances

Since I'm teaching a computing class this morning, here is a purely computer programming related post.  One of the students was having a problem with his code, using a do-while construct in the Fortran language.  This runs a block of code while a certain condition is true.  Here is a full example program which you can compile with e.g. the free gcc compiler:

PROGRAM dowhile

  IMPLICIT NONE
  INTEGER :: i, j

  i=1
  j=2
  DO WHILE (i<5)
     i=10
     j=20
  END DO
  WRITE(6,*) i, j

END PROGRAM dowhile


Now, the DO WHILE construct says that we run the code between the DO and END DO statements until the variable i is less than 5.  One may wonder, then, in the example, what value of j will be printed after exiting the loop.  If you know the rule that Fortran works by, then you know that the check of the condition i<5 takes place only each time the loop starts, and not continuously, so the line j=20 gets executed even though i<5 is no longer true at that point.  It is perhaps a little counter-intuitive, and can certainly lead to mistakes.  For that reason, I don't teach the DO WHILE construct in the year 1 computing course, but instead  "IF (i<5) exit", which can be inserted wherever in the loop the user wants the test to be done.  Enterprising students will, of course, find out about DO WHILE on the internet and make use of it.