The material is intended to supplement the textbook by providing further examples and discussion. It is not self-standing, but assumes that you have a copy of the book to hand.
Once you have experience in one language, it should be possible to work out the meaning of constructs in similar languages. The following Algol 60, Ada and Pascal program fragments should not therefore cause any problems.
sum := 0.0; for i := 0.1 step 0.2 until 0.9 do sum := sum + i sum = 0.0; for (double i = 0.1; i <= 0.9; i += 0.2) sum += i;Which is the easier to understand?
How many times will you go round these loops? Why is the answer implementation dependent?
An aim in language design is that there should be no unpleasant surprises. What therefore do you conclude about the desirability of allowing loop control variables to take fractional values?
int total = 0; for (int i = 1; total < 100; i++) total += i;Do you think that the following equivalent code is clearer?
int total = 0; int i = 1;
while (total < 100) {
total += i;
i++;
}
In Pascal, the second form must be used.
Is it a good idea to restrict for loops to be counting loops?
sum := 0; for i := 1 to 10 do sum := sum + ithe value of the loop control variable i is undefined. After the equivalent BASIC program, it would be 11. Which is preferable?
Is it reasonable to assume that we do not want to use the value of a loop control variable after we have left the loop?
Should languages attempt to protect programmers from doing silly things? If so, is it a good idea that a variable may become undefined during execution of a program.
What happens to the loop control variable after execution of the following Java (or C++) loop?
sum = 0; for (int i = 1; i <=10; i++) sum += i;Is that the solution to the above problem?
The following Ada loop has the same effect as the Java loop. In particular, the loop control variable i is implicitly declared and can only be used within the loop.
sum := 0; for i in 1 .. 10 loop sum := sum + i; end loop;Which for loop do you think is the simplest to understand?