Loops/For with a specified step: Difference between revisions

(→‎{{header|Ada}}: Added incorrect template)
Line 2:
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, we have to provide a range of even values to the loop, or multiply each value by two to get the same result.
{{incorrect|Ada|Ada does not allow integer literals in an enumeration type, only identifiers and character literals.}}
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 particular 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.
 
<lang ada>with Loopers;
In the declarative section:
use Loopers;
<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.
 
 
The following code prints multiples of three from 3 to 12:
procedure For_Main is
<lang ada>for Value in 3 .. 12 loop
begin
if Value mod 3 = 0 then
put(Value, 0) Looper_1;
put(", ") Looper_2;
end ifFor_Main;
 
end loop;
 
put("what's a word that rhymes with ""twelve""?");</lang>
package Loopers is
procedure Looper_1;
procedure Looper_2;
end loopLoopers;
 
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
 
package body Loopers is
procedure Looper_1 is
Values : array(1..5) of Integer := (2,4,6,8,10);
begin
for I in Values'Range loop
Put(Values(I),0);
if I = Values'Last then
Put_Line(".");
else
Put(",");
end if;
end loop;
end Looper_1;
 
procedure Looper_2 is
E : Integer := 5;
begin
for I in 1..E loop
Put(I*2,0);
if I = E then
Put_Line(".");
else
Put(",");
end if;
end loop;
end Looper_2;
end loopLoopers;
 
 
</lang>
 
=={{header|Aime}}==
Anonymous user