Loops/For with a specified step: Difference between revisions

no edit summary
No edit summary
Line 1:
{{task|Iteration}}
Demonstrate a for loop where the step value is greater than one.
=={{header|Ada}}==
The FOR loop construct in Ada does not give the programmer the ability to directly modify the loop control variable during the execution of the loop. Instead, Ada automatically takes care of the modification of the loop control variable by incrementing it or decrementing it to be the next value in a specified discrete sequence. For this reason, in a "real" program, an Ada programmer would use a WHILE loop, or more likely a general LOOP, construct to perform this task. For the sake of this task, however, the following code demonstrates a way the task could be performed, when the range of loop control values is sufficiently small, through the definition of an enumeration type.<br /><br />
In the declarative section:
<lang ada>
type Loop_Steps is (2, 4, 6, 8);
</lang>
In the body section:
<lang ada>
for Step in Loop_Steps loop
put(Step, 0);
put(", ");
end loop;
put("who do we appreciate?");
</lang>
Another way to do this, which would be more practical for larger ranges, is to loop through all of the values in a range (even the ones we weren't interested in using) and use a conditional check to determine whether or not to use the current loop control variable at each iteration. This is rather inefficient, growing more so as the step values get larger, but it's still order of O(n). Again, this is purely academic, since an actual Ada programmer would rarely do something like this.<br /><br />
The following code prints multiples of three from 3 to 12:
<lang ada>
for Value in 3 .. 12 loop
if Value mod 3 = 0 then
put(Value, 0);
put(", ")
end if;
end loop;
put("what's a word that rhymes with ""twelve""?");
</lang>
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
Anonymous user