"for", "for-downto" and "while" loops |
Both Pascal and "C/C++" have constructs for the FOR loop.
The Pascal construct is of the form
for count = startvalue to limitvalue do begin Body of the loop end
Because of the historical relationship between "C/C++" and assembly language, the syntax here is more explicit on the necessary operations to handle the loop
for (count = startvalue; count < limitvalue; count += increment ) { Body of the loop }
Each of these loops involves the following steps
Note that if the loop variable count is greater than the limitvalue initially, the loop never executes at all.
As will be seen shortly, except for the initializing the loop variable, the for-loop has the same format as the while-loop.
Pascal has an explicit construct of this form
for count = startvalue downto limitvalue do begin Body of the loop end
while "C/C++" language must be given that "downto" form by the programmer
for (count = startvalue; count > limitvalue; count -= decrement ) { Body of the loop }
Each of these loops involves the following steps
Note that, like the for-loop, this loop may never execute at all. It does not execute if the loop variable is less than the limitvalue initially,
Again, except for the initializing the loop variable, the for-downto loop can be shown to have essentially the same format as the while-loop.
Personally, when I'm doing "C" programming, it is only occasionally that I will find a direct use of this downcounting loop. It might be said that for-downto loops are ROCKET SCIENCE as counting up seems so much more natural.
However, because of the way processor instructions work, for-downto loops can be customized in assembly code to run faster (have less loop overhead) than for (up-counting) loops. We shall discuss the concept when we look at customizing loops for speed. The speed improvement is not worth worrying about unless you have
The while loop has the form
while (count < limitvalue) { Body of the loop }
This loop involves the following steps
Note that, like the for and for-downto loops, the while loop may never execute.
Unlike the other loops, there is not a regular approach to when and how to modify the while-loop variable so that the conditions of the loop while change and the loop executes. The programmer has to explicitly do something, whilst in the other loops, the variable change is part of the syntax for the loop.
A common error with the while loop is forgetting to program this change. However, just because you remember to change the loop-variable does not mean that the loop will work properly!
![]() |
Last modified: July 16, 1996 11:15 PM by M. Smith. Copyright -- M. R. Smith