Loops/For with a specified step: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added solution for Action!)
(Zig version with for-loop added)
 
(43 intermediate revisions by 25 users not shown)
Line 26: Line 26:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>L(i) (1..9).step(2)
<syntaxhighlight lang="11l">L(i) (1..9).step(2)
print(i)</lang>
print(i)</syntaxhighlight>


{{out}}
{{out}}
Line 41: Line 41:
;Basic - Algol style
;Basic - Algol style
The opcode BXH uses 3 registers, one for index one for step and one for limit.
The opcode BXH uses 3 registers, one for index one for step and one for limit.
<lang 360asm>* Loops/For with a specified step 12/08/2015
<syntaxhighlight lang="360asm">* Loops/For with a specified step 12/08/2015
LOOPFORS CSECT
LOOPFORS CSECT
USING LOOPFORS,R12
USING LOOPFORS,R12
Line 60: Line 60:
XDEC DS CL12 temp for edit
XDEC DS CL12 temp for edit
YREGS
YREGS
END LOOPFORS</lang>
END LOOPFORS</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 67: Line 67:
;Basic - Fortran style
;Basic - Fortran style
The opcode BXLE uses 3 registers, one for index one for step and one for limit.
The opcode BXLE uses 3 registers, one for index one for step and one for limit.
<lang 360asm>* == Fortran style ============== test at the end
<syntaxhighlight lang="360asm">* == Fortran style ============== test at the end
LA R3,BUF idx=0
LA R3,BUF idx=0
LA R5,5 from 5
LA R5,5 from 5
Line 76: Line 76:
LA R3,4(R3) idx=idx+4
LA R3,4(R3) idx=idx+4
BXLE R5,R6,LOOPJ next j
BXLE R5,R6,LOOPJ next j
XPRNT BUF,80 print buffer</lang>
XPRNT BUF,80 print buffer</syntaxhighlight>
;Structured Macros
;Structured Macros
<lang 360asm>* == Algol style ================ test at the beginning
<syntaxhighlight lang="360asm">* == Algol style ================ test at the beginning
LA R3,BUF idx=0
LA R3,BUF idx=0
LA R5,5 from 5
LA R5,5 from 5
Line 89: Line 89:
AR R5,R6 i=i+step
AR R5,R6 i=i+step
ENDDO , next i
ENDDO , next i
XPRNT BUF,80 print buffer</lang>
XPRNT BUF,80 print buffer</syntaxhighlight>
;Structured Macros HLASM
;Structured Macros HLASM
<lang 360asm>* == Fortran style ============== test at the end
<syntaxhighlight lang="360asm">* == Fortran style ============== test at the end
LA R3,BUF idx=0
LA R3,BUF idx=0
DO FROM=(R5,5),TO=(R7,25),BY=(R6,5) for i=5 to 25 step 5
DO FROM=(R5,5),TO=(R7,25),BY=(R6,5) for i=5 to 25 step 5
Line 98: Line 98:
LA R3,4(R3) idx=idx+4
LA R3,4(R3) idx=idx+4
ENDDO , next i
ENDDO , next i
XPRNT BUF,80 print buffer</lang>
XPRNT BUF,80 print buffer</syntaxhighlight>
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
This loop loads from an array and writes each element to memory addresses $D000, $D002, $D004, $D006, $D008, $D00A, $D00C, $D00E, in ascending order.
This loop loads from an array and writes each element to memory addresses $D000, $D002, $D004, $D006, $D008, $D00A, $D00C, $D00E, in ascending order.


<lang 6502asm>define ArrayPointerLo $00 ;define some helpful labels.
<syntaxhighlight lang="6502asm">define ArrayPointerLo $00 ;define some helpful labels.
define ArrayPointerHi $01
define ArrayPointerHi $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 147: Line 147:
bpl loop_fill ;if destination index equals #$FF, we are done.
bpl loop_fill ;if destination index equals #$FF, we are done.


brk ;end of program</lang>
brk ;end of program</syntaxhighlight>


{{out}}
{{out}}
Line 156: Line 156:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program loopstep64.s */
/* program loopstep64.s */
Line 209: Line 209:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
BYTE i
BYTE i


Line 219: Line 219:
PrintF("%B ",i)
PrintF("%B ",i)
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/For_with_a_specified_step.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/For_with_a_specified_step.png Screenshot from Atari 8-bit computer]
Line 233: Line 233:
Looper_3 most closely adheres to the requirements of this task, and achieves this by using a second range for the indices.
Looper_3 most closely adheres to the requirements of this task, and achieves this by using a second range for the indices.


<lang ada>with Loopers;
<syntaxhighlight lang="ada">with Loopers;
use Loopers;
use Loopers;


Line 297: Line 297:
end Loopers;
end Loopers;


</syntaxhighlight>
</lang>


=={{header|Agena}}==
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
Tested with Agena 2.9.5 Win32
<lang agena>for i from 2 to 8 by 2 do
<syntaxhighlight lang="agena">for i from 2 to 8 by 2 do
print( i )
print( i )
od</lang>
od</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>integer i;
<syntaxhighlight lang="aime">integer i;


i = 0;
i = 0;
Line 314: Line 314:
}
}


o_newline();</lang>
o_newline();</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
Line 357: Line 357:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
for i := 3 step 2 until 9 do write( i )
for i := 3 step 2 until 9 do write( i )
end.</lang>
end.</syntaxhighlight>


=={{header|ALGOL-M}}==
=={{header|ALGOL-M}}==
<lang algol>BEGIN
<syntaxhighlight lang="algol">BEGIN
INTEGER I;
INTEGER I;
FOR I := 1 STEP 3 UNTIL 19 DO
FOR I := 1 STEP 3 UNTIL 19 DO
WRITE( I );
WRITE( I );
END</lang>
END</syntaxhighlight>


=={{header|AppleScript|}}==
=={{header|AppleScript}}==


<lang AppleScript>repeat with i from 2 to 10 by 2
<syntaxhighlight lang="applescript">repeat with i from 2 to 10 by 2
log i
log i
end repeat</lang>
end repeat</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 516: Line 516:




</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>loop 0..10 .step:2 'i [
<syntaxhighlight lang="rebol">loop 0..10 .step:2 'i [
print i
print i
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>0
<pre>0
Line 531: Line 531:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>SetBatchLines, -1
<syntaxhighlight lang="autohotkey">SetBatchLines, -1
iterations := 5
iterations := 5
step := 10
step := 10
Line 541: Line 541:
MsgBox, % A_Index
MsgBox, % A_Index
}
}
ExitApp</lang>
ExitApp</syntaxhighlight>


=={{header|Avail}}==
=={{header|Avail}}==
<lang Avail>For each i from 0 to 100 by 7 do [Print: “i” ++ " is a multiple of 7!\n";];</lang>
<syntaxhighlight lang="avail">For each i from 0 to 100 by 7 do [Print: “i” ++ " is a multiple of 7!\n";];</syntaxhighlight>
Note the <code>0 to 100 by 7</code> segment isn't a fixed part of the loop syntax, but a call to the <code>_to_by_</code> method, which returns a tuple of integers in a range separated by a particular step size.
Note the <code>0 to 100 by 7</code> segment isn't a fixed part of the loop syntax, but a call to the <code>_to_by_</code> method, which returns a tuple of integers in a range separated by a particular step size.


=={{header|AWK}}==
=={{header|AWK}}==


<lang awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
for (i= 2; i <= 8; i = i + 2) {
for (i= 2; i <= 8; i = i + 2) {
print i
print i
}
}
print "Ain't never too late!"
print "Ain't never too late!"
}</lang>
}</syntaxhighlight>


Line 561: Line 561:


This example increments by 2:
This example increments by 2:
<lang axe>For(I,0,10)
<syntaxhighlight lang="axe">For(I,0,10)
Disp I▶Dec,i
Disp I▶Dec,i
I++
I++
End</lang>
End</syntaxhighlight>

=={{header|Bait}}==
<syntaxhighlight lang="bait">
fun main() {
// Print all single digit odd numbers
for i := 1; i < 10; i += 2 {
println(i)
}
}
</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang qbasic>FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?"</lang>
<syntaxhighlight lang="qbasic">FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?"</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
This prints all odd digits:
This prints all odd digits:
<lang freebasic>
<syntaxhighlight lang="freebasic">
FOR i = 1 TO 10 STEP 2
FOR i = 1 TO 10 STEP 2
PRINT i
PRINT i
NEXT</lang>
NEXT</syntaxhighlight>


==={{header|Basic|QuickBasic}}===
==={{header|Basic|QuickBasic}}===
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>for i = 2 to 8 step 2
<syntaxhighlight lang="qbasic">for i = 2 to 8 step 2
print i; ", ";
print i; ", ";
next i
next i
print "who do we appreciate?"</lang>
print "who do we appreciate?"</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang BASIC256>for i = 1 to 21 step 2
<syntaxhighlight lang="basic256">for i = 1 to 21 step 2
print i; " ";
print i; " ";
next i
next i
end</lang>
end</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> FOR n = 2 TO 8 STEP 1.5
<syntaxhighlight lang="bbcbasic"> FOR n = 2 TO 8 STEP 1.5
PRINT n
PRINT n
NEXT</lang>
NEXT</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 602: Line 612:
8
8
</pre>
</pre>

==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 for i = 1 to 21 step 2
20 print i;
30 next i</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang qbasic>10 FOR I = 1 TO 10 STEP 2
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 10 STEP 2
20 PRINT I
20 PRINT I
30 NEXT</lang>
30 NEXT</syntaxhighlight>


==={{header|FreeBASIC}}===
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


For i As Integer = 1 To 21 Step 2
For i As Integer = 1 To 21 Step 2
Line 615: Line 631:
Next
Next
Print
Print
Sleep</lang>
Sleep</syntaxhighlight>

==={{header|FutureBasic}}===
<lang futurebasic>
include "ConsoleWindow"

dim as Str15 s(11)
dim as long i

s(0) = "Somewhere"
s(2) = " over"
s(4) = " the"
s(6) = " rainbow" + chr$(13)
s(8) = "Bluebirds"
s(10) = " fly."

for i = 0 to 10 step 2
print s(i);
next
</lang>
Output:
<pre>
Somewhere over the rainbow
Bluebirds fly.
</pre>


==={{header|Gambas}}===
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=cdd9b10b64ac4d78b75c364061f25641 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=cdd9b10b64ac4d78b75c364061f25641 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
Dim siCount As Short


Line 650: Line 642:
Next
Next


End</lang>
End</syntaxhighlight>
<pre>
<pre>Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Line 660: Line 652:
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!</pre>

Gambas is great!
==={{header|GW-BASIC}}===
</pre>
{{works with|BASICA}}
{{works with|PC-BASIC|any}}
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 21 STEP 2
20 PRINT I;
30 NEXT I</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 FOR I=1 TO 10 STEP 2
<syntaxhighlight lang="is-basic">100 FOR I=1 TO 10 STEP 2
110 PRINT I
110 PRINT I
120 NEXT</lang>
120 NEXT</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">for i = 2 to 8 step 2
<lang lb>
for i = 2 to 8 step 2
print i; ", ";
print i; ", ";
next i
next i
print "who do we appreciate?"
print "who do we appreciate?"
end</syntaxhighlight>
end
</lang>


==={{header|Microsoft Small Basic}}===
==={{header|Microsoft Small Basic}}===
<lang microsoftsmallbasic>
<syntaxhighlight lang="microsoftsmallbasic">For i = 0 To 100 Step 2
For i = 0 To 100 Step 2
TextWindow.WriteLine(i)
TextWindow.WriteLine(i)
EndFor
EndFor</syntaxhighlight>

</lang>
==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
{{works with|Run BASIC}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 21 STEP 2
20 PRINT I; " ";
30 NEXT I
40 END</syntaxhighlight>

==={{header|MSX Basic}}===
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 21 STEP 2
20 PRINT I;
30 NEXT I</syntaxhighlight>


==={{header|NS-HUBASIC}}===
==={{header|NS-HUBASIC}}===
<lang NS-HUBASIC>10 FOR I=1 TO 10 STEP 2
<syntaxhighlight lang="ns-hubasic">10 FOR I=1 TO 10 STEP 2
20 PRINT I
20 PRINT I
30 NEXT</lang>
30 NEXT</syntaxhighlight>

{{out}}
{{out}}
<pre> 1 3 5 7 9 11 13 15 17 19 21</pre>
<pre>
1 3 5 7 9 11 13 15 17 19 21
</pre>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
<lang PureBasic>For i=-15 To 25 Step 5
<syntaxhighlight lang="purebasic">For i = -15 To 25 Step 5
Debug i
Debug i
Next i</lang>
Next i</syntaxhighlight>
{{out}}
<pre>-15
-10
-5
0
5
10
15
20
25</pre>

Decrementing with step
<syntaxhighlight lang="purebasic">For i = 10 To 0 Step -2
Debug i
Next ; i is optional</syntaxhighlight>
{{out}}
<pre>10
8
6
4
2
0</pre>


==={{header|QB64}}===
==={{header|QB64}}===
<lang QB64>For i% = 0 to 10 Step 2
<syntaxhighlight lang="qbasic">For i% = 0 to 10 Step 2
Print i%
Print i%
Next 'To be more explicit use "Next i%"
Next 'To be more explicit use "Next i%"
</syntaxhighlight>
</lang>
{{out}}
{{out}}
A newline is inserted automatically after the Print statement
A newline is inserted automatically after the Print statement
<pre>
<pre>0
0
2
2
4
4
6
6
8
8
10
10</pre>

</pre>
We can also decrement with stepping
<syntaxhighlight lang="qbasic">For i% = 10 to 0 Step -2
Print i%
Next i </syntaxhighlight>
{{out}}
<pre>10
8
6
4
2
9</pre>

==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">FOR i = 1 TO 21 STEP 2
PRINT i;
NEXT i</syntaxhighlight>

==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 FOR I = 1 TO 21 STEP 2
20 PRINT I; " ";
30 NEXT I</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>for i = 2 to 8 step 2
<syntaxhighlight lang="runbasic">for i = 2 to 8 step 2
print i; ", ";
print i; ", ";
next i
next i
print "who do we appreciate?"</lang>
print "who do we appreciate?"</syntaxhighlight>
{{out}}
{{out}}
<pre>2, 4, 6, 8, who do we appreciate?</pre>
<pre>2, 4, 6, 8, who do we appreciate?</pre>
Line 727: Line 783:
Notice how the ampersand (&) is used to concatenate the variable with the text instead of a semicolon.
Notice how the ampersand (&) is used to concatenate the variable with the text instead of a semicolon.


<lang qbasic>FOR n = 2 TO 8 STEP 2
<syntaxhighlight lang="qbasic">FOR n = 2 TO 8 STEP 2
PRINT n & "..";
PRINT n & "..";
NEXT n
NEXT n
PRINT "who do we appreciate?"
PRINT "who do we appreciate?"
END</lang>
END</syntaxhighlight>


==={{header|TI-83 BASIC}}===
==={{header|TI-83 BASIC}}===
Prints numbers from 0 to 100 stepping by 5.
Prints numbers from 0 to 100 stepping by 5.
<lang ti83b>:For(I,0,100,5
<syntaxhighlight lang="ti83b">:For(I,0,100,5
:Disp I
:Disp I
:End</lang>
:End</syntaxhighlight>


==={{header|TI-89 BASIC}}===
==={{header|TI-89 BASIC}}===
<lang ti89b>Local i
<syntaxhighlight lang="ti89b">Local i
For i, 0, 100, 5
For i, 0, 100, 5
Disp i
Disp i
EndFor</lang>
EndFor</syntaxhighlight>

==={{Header|Tiny BASIC}}===
<syntaxhighlight lang="qbasic"> REM TinyBasic does not have a for-loop construct.
REM Equivalent using conditional jump:

LET i = 1
10 IF i > 21 THEN GOTO 20
PRINT i
LET i = i + 2
GOTO 10
20 END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">
<lang basic>
FOR i = 1 TO 21 STEP 2
FOR i = 1 TO 21 STEP 2
PRINT i; " ";
PRINT i; " ";
NEXT i
NEXT i
END
END
</syntaxhighlight>
</lang>
{{out}}
<pre>1 3 5 7 9 11 13 15 17 19 21</pre>
Since TrueBasic does not distinguish between integer or real values, we can increment using decimal values as well

<syntaxhighlight lang="qbasic">FOR i = 1 TO 5 STEP .5
PRINT i
NEXT i
END</syntaxhighlight>
{{out}}
<pre>1
1.5
2
2.5
3
3.5
4
4.5
5</pre>


==={{header|Visual Basic}}===
==={{header|Visual Basic}}===
{{works with|Visual Basic|VB6 Standard}}
{{works with|Visual Basic|VB6 Standard}}
<lang vb>Sub MyLoop()
<syntaxhighlight lang="vb">Sub MyLoop()
For i = 2 To 8 Step 2
For i = 2 To 8 Step 2
Debug.Print i;
Debug.Print i;
Next i
Next i
Debug.Print
Debug.Print
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre> 2 4 6 8 </pre>
2 4 6 8
</pre>


==={{header|Visual Basic .NET}}===
==={{header|Visual Basic .NET}}===
{{works with|Visual Basic .NET|.NET Core 3.0}}
{{works with|Visual Basic .NET|.NET Core 3.0}}
<lang vbnet>Imports System.Console
<syntaxhighlight lang="vbnet">Imports System.Console
Module Program
Module Program
Sub Main()
Sub Main()
Line 776: Line 859:
WriteLine("who do we appreciate?")
WriteLine("who do we appreciate?")
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>
{{out}}
{{out}}
<pre>2, 4, 6, 8, who do we appreciate?</pre>
<pre>
2, 4, 6, 8, who do we appreciate?
</pre>


{{works with|Visual Basic .NET|2011}}
{{works with|Visual Basic .NET|2011}}
<lang vbnet>Public Class FormPG
<syntaxhighlight lang="vbnet">Public Class FormPG
Private Sub FormPG_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Private Sub FormPG_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim i As Integer, buffer As String
Dim i As Integer, buffer As String
Line 792: Line 873:
Debug.Print(buffer)
Debug.Print(buffer)
End Sub
End Sub
End Class</lang>
End Class</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>2 4 6 8 </pre>
2 4 6 8
</pre>


==={{header|XBasic}}===
==={{header|XBasic}}===
{{works with|Windows XBasic}}
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "forby"
<lang xbasic>
PROGRAM "forby"


DECLARE FUNCTION Entry()
DECLARE FUNCTION Entry()
Line 810: Line 888:
NEXT i%
NEXT i%
END FUNCTION
END FUNCTION
END PROGRAM
END PROGRAM</syntaxhighlight>
</lang>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang Yabasic>for i = 1 to 21 step 2
<syntaxhighlight lang="yabasic">for i = 1 to 21 step 2
print i, " ";
print i, " ";
next i
next i
print
print
end</lang>
end</syntaxhighlight>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
<lang basic>10 FOR l = 2 TO 8 STEP 2
<syntaxhighlight lang="basic">10 FOR l = 2 TO 8 STEP 2
20 PRINT l; ", ";
20 PRINT l; ", ";
30 NEXT l
30 NEXT l
40 PRINT "Who do we appreciate?"</lang>
40 PRINT "Who do we appreciate?"</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
for /l %%A in (1,2,10) do (
for /l %%A in (1,2,10) do (
echo %%A
echo %%A
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>>Sample.BAT
<pre>>Sample.BAT
Line 842: Line 919:


=={{header|bc}}==
=={{header|bc}}==
<lang bc>for (i = 2; i <= 10; i += 2) {
<syntaxhighlight lang="bc">for (i = 2; i <= 10; i += 2) {
i
i
}</lang>
}</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
{{trans|C}}
{{trans|C}}
<lang befunge>1 >:.55+,v
<syntaxhighlight lang="befunge">1 >:.55+,v
@_^#`9:+2<</lang>
@_^#`9:+2<</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
This prints all odd digits:
This prints all odd digits:
<lang c>int i;
<syntaxhighlight lang="c">int i;
for(i = 1; i < 10; i += 2)
for(i = 1; i < 10; i += 2)
printf("%d\n", i);</lang>
printf("%d\n", i);</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
class Program {
class Program {
Line 869: Line 946:
Console.WriteLine("who do we appreciate?");
Console.WriteLine("who do we appreciate?");
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
This prints all odd digits:
This prints all odd digits:
<lang cpp>for (int i = 1; i < 10; i += 2)
<syntaxhighlight lang="cpp">for (int i = 1; i < 10; i += 2)
std::cout << i << std::endl;</lang>
std::cout << i << std::endl;</syntaxhighlight>

=={{header|C3}}==
Print all odd digits:
<syntaxhighlight lang="c3">for (int i = 1; i < 10; i += 2) io::printfn("%d", i);</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
for(i in (2..8).by(2)) {
for(i in (2..8).by(2)) {
Line 883: Line 964:
}
}
print("who do we appreciate?");
print("who do we appreciate?");
}</lang>
}</syntaxhighlight>


=={{header|Chapel}}==
=={{header|Chapel}}==
<lang chapel>
<syntaxhighlight lang="chapel">
// Can be set on commandline via --N=x
// Can be set on commandline via --N=x
config const N = 3;
config const N = 3;
Line 893: Line 974:
writeln(i);
writeln(i);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 910: Line 991:
=={{header|ChucK}}==
=={{header|ChucK}}==
Chuck style
Chuck style
<syntaxhighlight lang="c">
<lang c>
SinOsc s => dac;
SinOsc s => dac;


Line 918: Line 999:
100::ms => now;
100::ms => now;
}
}
</syntaxhighlight>
</lang>
General purpose style:
General purpose style:
<syntaxhighlight lang="c">
<lang c>
for (0 => int i; i < 2000; 5 +=> i )
for (0 => int i; i < 2000; 5 +=> i )
{
{
<<< i >>>;
<<< i >>>;
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
The first example here is following the literal specification, but is not idiomatic Clojure code.
The first example here is following the literal specification, but is not idiomatic Clojure code.
The second example achieves the same effect without explicit looping, and would (I think) be viewed as better code by the Clojure community.
The second example achieves the same effect without explicit looping, and would (I think) be viewed as better code by the Clojure community.
<lang Clojure>(loop [i 0]
<syntaxhighlight lang="clojure">(loop [i 0]
(println i)
(println i)
(when (< i 10)
(when (< i 10)
Line 936: Line 1,017:


(doseq [i (range 0 12 2)]
(doseq [i (range 0 12 2)]
(println i))</lang>
(println i))</syntaxhighlight>

=={{header|CLU}}==
<syntaxhighlight lang="clu">% This prints all odd digits

start_up = proc ()
po: stream := stream$primary_output()
for i: int in int$from_to_by(1, 10, 2) do
stream$putl(po, int$unparse(i))
end
end start_up</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Display-Odd-Nums.
PROGRAM-ID. Display-Odd-Nums.


Line 952: Line 1,044:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<lang cfm>
<syntaxhighlight lang="cfm">
<cfloop from="0" to="99" step="3" index="i">
<cfloop from="0" to="99" step="3" index="i">
<Cfoutput>#i#</Cfoutput>
<Cfoutput>#i#</Cfoutput>
</cfloop>
</cfloop>
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(format t "~{~S, ~}who do we appreciate?~%" (loop for i from 2 to 8 by 2 collect i))
(format t "~{~S, ~}who do we appreciate?~%" (loop for i from 2 to 8 by 2 collect i))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 972: Line 1,064:


=== Using DO ===
=== Using DO ===
<lang lisp>
<syntaxhighlight lang="lisp">
(do ((n 0 (incf n (+ (random 3) 2)))) ; Initialize to 0 and set random step-value 2, 3 or 4
(do ((n 0 (incf n (+ (random 3) 2)))) ; Initialize to 0 and set random step-value 2, 3 or 4
((> n 20)) ; Break condition
((> n 20)) ; Break condition
(print n)) ; On every loop print value
(print n)) ; On every loop print value
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 992: Line 1,084:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.range;
<syntaxhighlight lang="d">import std.stdio, std.range;


void main() {
void main() {
Line 1,002: Line 1,094:
foreach (i; iota(1, 10, 2))
foreach (i; iota(1, 10, 2))
writeln(i);
writeln(i);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,016: Line 1,108:


=={{header|Dao}}==
=={{header|Dao}}==
<lang dao># first value: 1
<syntaxhighlight lang="dao"># first value: 1
# max value: 9
# max value: 9
# step: 2
# step: 2
for( i = 1 : 2 : 9 ) io.writeln( i )</lang>
for( i = 1 : 2 : 9 ) io.writeln( i )</syntaxhighlight>

=={{header|Dart}}==
<syntaxhighlight lang="dart">main() {
for (int i = 1; i <= 21; i += 2) print(i);
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 1,025: Line 1,122:
It would have to be simulated using something like a While loop.
It would have to be simulated using something like a While loop.


<lang Delphi>program LoopWithStep;
<syntaxhighlight lang="delphi">program LoopWithStep;
{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,037: Line 1,134:
Inc(i, 2);
Inc(i, 2);
end;
end;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>2
<pre>2
Line 1,045: Line 1,142:


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>for(i = 2, i <= 8,i += 2){
<syntaxhighlight lang="dragon">for(i = 2, i <= 8,i += 2){
show ", " + i
show ", " + i
}
}
showln "who do we appreciate?"</lang>
showln "who do we appreciate?"</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang Delphi>var i : Integer;
<syntaxhighlight lang="delphi">var i : Integer;


for i := 2 to 8 step 2 do
for i := 2 to 8 step 2 do
PrintLn(i);</lang>
PrintLn(i);</syntaxhighlight>


{{out}}
{{out}}
Line 1,061: Line 1,158:
6
6
8</pre>
8</pre>

=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">//Prints odd numbers from 1 to 10
for i in 1^2..10 {
print(i)
}</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
There is no step in the standard numeric range object (a..b and a..!b) in E, which is typically used for numeric iteration.
There is no step in the standard numeric range object (a..b and a..!b) in E, which is typically used for numeric iteration.
An ordinary while loop can of course be used:
An ordinary while loop can of course be used:
<lang e>var i := 2
<syntaxhighlight lang="e">var i := 2
while (i <= 8) {
while (i <= 8) {
print(`$i, `)
print(`$i, `)
i += 2
i += 2
}
}
println("who do we appreciate?")</lang>
println("who do we appreciate?")</syntaxhighlight>


A programmer frequently in need of iteration with an arbitrary step should define an appropriate range object:
A programmer frequently in need of iteration with an arbitrary step should define an appropriate range object:


<lang e>def stepRange(low, high, step) {
<syntaxhighlight lang="e">def stepRange(low, high, step) {
def range {
def range {
to iterate(f) {
to iterate(f) {
Line 1,090: Line 1,193:
print(`$i, `)
print(`$i, `)
}
}
println("who do we appreciate?")</lang>
println("who do we appreciate?")</syntaxhighlight>


The least efficient, but perhaps convenient, solution is to iterate over successive integers and discard undesired ones:
The least efficient, but perhaps convenient, solution is to iterate over successive integers and discard undesired ones:


<lang e>for i ? (i %% 2 <=> 0) in 2..8 {
<syntaxhighlight lang="e">for i ? (i %% 2 <=> 0) in 2..8 {
print(`$i, `)
print(`$i, `)
}
}
println("who do we appreciate?")</lang>
println("who do we appreciate?")</syntaxhighlight>

=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
# Prints even numbers from 0 to 100
for i = 0 step 2 to 100
print i
.
</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
Steps may be integers, float, rationals.
Steps may be integers, float, rationals.
<lang lisp>
<syntaxhighlight lang="lisp">
(for ((i (in-range 0 15 2))) (write i))
(for ((i (in-range 0 15 2))) (write i))
0 2 4 6 8 10 12 14
0 2 4 6 8 10 12 14
Line 1,110: Line 1,221:
(for ((x (in-range 0 15 PI))) (write x))
(for ((x (in-range 0 15 PI))) (write x))
0 3.141592653589793 6.283185307179586 9.42477796076938 12.566370614359172
0 3.141592653589793 6.283185307179586 9.42477796076938 12.566370614359172
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==


<lang ela>open monad io
<syntaxhighlight lang="ela">open monad io
for m s n | n > m = do return ()
for m s n | n > m = do return ()
Line 1,121: Line 1,232:
for m s (n+s)
for m s (n+s)
_ = for 10 2 0 ::: IO</lang>
_ = for 10 2 0 ::: IO</syntaxhighlight>


{{out}}
{{out}}
Line 1,132: Line 1,243:


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x
ELENA 6.x
<lang elena>public program()
<syntaxhighlight lang="elena">public program()
{
{
for(int i := 2, i <= 8, i += 2 )
for(int i := 2; i <= 8; i += 2 )
{
{
console.writeLine:i
console.writeLine(i)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Loops do
<syntaxhighlight lang="elixir">defmodule Loops do
def for_step(n, step) do
def for_step(n, step) do
IO.inspect Enum.take_every(1..n, step)
IO.inspect Enum.take_every(1..n, step)
Line 1,148: Line 1,259:
end
end


Loops.for_step(20, 3)</lang>
Loops.for_step(20, 3)</syntaxhighlight>


{{out}}
{{out}}
Line 1,155: Line 1,266:
</pre>
</pre>
or
or
<lang elixir>iex(1)> Stream.iterate(1, &(&1+2)) |> Enum.take(10)
<syntaxhighlight lang="elixir">iex(1)> Stream.iterate(1, &(&1+2)) |> Enum.take(10)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]</lang>
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]</syntaxhighlight>

=={{header|EMal}}==
<syntaxhighlight lang="emal">
for int i = 2; i <= 8; i+= 2 do write(i + ", ") end
writeLine("who do we appreciate?")
</syntaxhighlight>
{{out}}
<pre>
2, 4, 6, 8, who do we appreciate?
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>%% Implemented by Arjun Sunel
<syntaxhighlight lang="erlang">%% Implemented by Arjun Sunel
%% for_loop/4 by Bengt Kleberg.
%% for_loop/4 by Bengt Kleberg.
-module(loop_step).
-module(loop_step).
Line 1,176: Line 1,297:
for_loop( I+Step, End, Step, Do );
for_loop( I+Step, End, Step, Do );
for_loop( _I, _End, _Step, _Do ) -> ok.
for_loop( _I, _End, _Step, _Do ) -> ok.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,184: Line 1,305:


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
FOR N=2 TO 8 STEP 1.5 DO
FOR N=2 TO 8 STEP 1.5 DO
PRINT(N)
PRINT(N)
END FOR
END FOR
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,200: Line 1,321:
=={{header|Euphoria}}==
=={{header|Euphoria}}==


<syntaxhighlight lang="euphoria">
<lang Euphoria>
for i = 1 to 10 by 2 do
for i = 1 to 10 by 2 do
? i
? i
end for
end for
</syntaxhighlight>
</lang>
As a note, <code>? something</code> is shorthand for:
As a note, <code>? something</code> is shorthand for:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
print(1, something)
print(1, something)
puts(1, "\n")
puts(1, "\n")
</syntaxhighlight>
</lang>


<code>print()</code> differs from <code>puts()</code> in that <code>print()</code> will print out the actual <code>sequence</code> it is given.
<code>print()</code> differs from <code>puts()</code> in that <code>print()</code> will print out the actual <code>sequence</code> it is given.
Line 1,216: Line 1,337:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>for i in 2..2..8 do
<syntaxhighlight lang="fsharp">for i in 2..2..8 do
printf "%d, " i
printf "%d, " i
printfn "done"</lang>
printfn "done"</syntaxhighlight>


{{out}}
{{out}}
Line 1,226: Line 1,347:
=={{header|Factor}}==
=={{header|Factor}}==
Prints odd digits.
Prints odd digits.
<lang factor>1 10 2 <range> [ . ] each</lang>
<syntaxhighlight lang="factor">1 10 2 <range> [ . ] each</syntaxhighlight>


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>2[$9\>][$.", "2+]#"who do we appreciate!"</lang>
<syntaxhighlight lang="false">2[$9\>][$.", "2+]#"who do we appreciate!"</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,245: Line 1,366:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|FBSL}}==
=={{header|FBSL}}==
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE


DIM n AS INTEGER
DIM n AS INTEGER
Line 1,257: Line 1,378:
PRINT ", who will we obliterate?"
PRINT ", who will we obliterate?"
PAUSE
PAUSE
</syntaxhighlight>
</lang>


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>for i = 1 to 100 by 13 do !i;!' '; od</lang>
<syntaxhighlight lang="fermat">for i = 1 to 100 by 13 do !i;!' '; od</syntaxhighlight>
{{out}}<pre>1 14 27 40 53 66 79 92</pre>
{{out}}<pre>1 14 27 40 53 66 79 92</pre>


=={{header|FOCAL}}==
=={{header|FOCAL}}==
If a <tt>FOR</tt> statement has three parameters, they are (in order) the start, the step, and the end; if only two parameters are supplied, they are taken to be the start and the end. The step is then set to 1.
If a <tt>FOR</tt> statement has three parameters, they are (in order) the start, the step, and the end; if only two parameters are supplied, they are taken to be the start and the end. The step is then set to 1.
<lang focal>FOR I = 1,3,10; TYPE I, !</lang>
<syntaxhighlight lang="focal">FOR I = 1,3,10; TYPE I, !</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: test
<syntaxhighlight lang="forth">: test
9 2 do
9 2 do
i .
i .
2 +loop
2 +loop
." who do we appreciate?" cr ;</lang>
." who do we appreciate?" cr ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>do i = 1,10,2
<syntaxhighlight lang="fortran">do i = 1,10,2
print *, i
print *, i
end do</lang>
end do</syntaxhighlight>


{{works with|Fortran|77 and later}}
{{works with|Fortran|77 and later}}
<lang fortran> PROGRAM STEPFOR
<syntaxhighlight lang="fortran"> PROGRAM STEPFOR
INTEGER I
INTEGER I


Line 1,290: Line 1,411:


STOP
STOP
END</lang>
END</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
for a = 1 to 100 step 5
for a = 1 to 100 step 5
println[a]
println[a]
</syntaxhighlight>
</lang>


All values may have units of measure, in which case a specified step is required:
All values may have units of measure, in which case a specified step is required:
<lang frink>
<syntaxhighlight lang="frink">
for a = 1 km to 3 km step 1 meter
for a = 1 km to 3 km step 1 meter
println[a]
println[a]
</syntaxhighlight>
</lang>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
Str15 s(11)
long i

s(0) = "Somewhere"
s(2) = " over"
s(4) = " the"
s(6) = " rainbow" + chr$(13)
s(8) = "Bluebirds"
s(10) = " fly."

for i = 0 to 10 step 2
print s(i);
next

HandleEvents
</syntaxhighlight>
{{out}}
<pre>Somewhere over the rainbow
Bluebirds fly.</pre>

=={{header|GML}}==
<syntaxhighlight lang="gml">for(i = 0; i < 10; i += 2)
show_message(string(i))</syntaxhighlight>


=={{header|GAP}}==
=={{header|GAP}}==
# Use a range [a, b .. c], where the step is b-a (b is the value following a), and c-a must be a multiple of the step.
# Use a range [a, b .. c], where the step is b-a (b is the value following a), and c-a must be a multiple of the step.
<lang gap>for i in [1, 3 .. 11] do
<syntaxhighlight lang="gap">for i in [1, 3 .. 11] do
Print(i, "\n");
Print(i, "\n");
od;
od;
Line 1,316: Line 1,463:
9
9
11
11
</syntaxhighlight>
</lang>

=={{header|GML}}==
<lang GML>for(i = 0; i < 10; i += 2)
show_message(string(i))</lang>


=={{header|Go}}==
=={{header|Go}}==
This prints all odd digits:
This prints all odd digits:
<lang go>for i := 1; i < 10; i += 2 {
<syntaxhighlight lang="go">for i := 1; i < 10; i += 2 {
fmt.Printf("%d\n", i)
fmt.Printf("%d\n", i)
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
"for" loop:
"for" loop:
<lang groovy>for(i in (2..9).step(2)) {
<syntaxhighlight lang="groovy">for(i in (2..9).step(2)) {
print "${i} "
print "${i} "
}
}
println "Who do we appreciate?"</lang>
println "Who do we appreciate?"</syntaxhighlight>


"each() method:
"each() method:
Though technically not a loop, most Groovy programmers would use the slightly more terse "each()" method on the collection itself, instead of a "for" loop.
Though technically not a loop, most Groovy programmers would use the slightly more terse "each()" method on the collection itself, instead of a "for" loop.
<lang groovy>(2..9).step(2).each {
<syntaxhighlight lang="groovy">(2..9).step(2).each {
print "${it} "
print "${it} "
}
}
println "Who do we appreciate?"</lang>
println "Who do we appreciate?"</syntaxhighlight>


{{out}}
{{out}}
Line 1,347: Line 1,490:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Monad (forM_)
<syntaxhighlight lang="haskell">import Control.Monad (forM_)
main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", "))
main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", "))
putStrLn "who do we appreciate?"</lang>
putStrLn "who do we appreciate?"</syntaxhighlight>


=={{header|Haxe}}==
=={{header|Haxe}}==
While Haxe's for-loop does not allow you to directly specify the step size, it is easy to create an iterator that allows you to do that.
While Haxe's for-loop does not allow you to directly specify the step size, it is easy to create an iterator that allows you to do that.


<lang haxe>class Step {
<syntaxhighlight lang="haxe">class Step {
var end:Int;
var end:Int;
var step:Int;
var step:Int;
Line 1,376: Line 1,519:
Sys.println('WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!');
Sys.println('WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!');
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,382: Line 1,525:


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>for let i 0; i <= 50; let i (i + 5)
<syntaxhighlight lang="hexiscript">for let i 0; i <= 50; let i (i + 5)
println i
println i
endfor</lang>
endfor</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>DO i = 1, 6, 1.25 ! from 1 to 6 step 1.25
<syntaxhighlight lang="hicest">DO i = 1, 6, 1.25 ! from 1 to 6 step 1.25
WRITE() i
WRITE() i
ENDDO</lang>
ENDDO</syntaxhighlight>


=={{header|HolyC}}==
=={{header|HolyC}}==
This prints all odd digits:
This prints all odd digits:
<lang holyc>U8 i;
<syntaxhighlight lang="holyc">U8 i;
for (i = 1; i < 10; i += 2)
for (i = 1; i < 10; i += 2)
Print("%d\n", i);</lang>
Print("%d\n", i);</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==
<lang clojure>(for [i (range 1 10 2)] (print i))</lang>
<syntaxhighlight lang="clojure">(for [i (range 1 10 2)] (print i))</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon accomplish loop stepping through the use of a generator, the ternary operator to-by, and the every clause which forces a generator to consume all of its results.
Icon and Unicon accomplish loop stepping through the use of a generator, the ternary operator to-by, and the every clause which forces a generator to consume all of its results.
Because to-by is an operator it has precedence (just higher than assignments) and associativity (left) and can be combined with other operators.
Because to-by is an operator it has precedence (just higher than assignments) and associativity (left) and can be combined with other operators.
<syntaxhighlight lang="python">
<lang Icon>
every 1 to 10 by 2 # the simplest case that satisfies the task, step by 2
every 1 to 10 by 2 # the simplest case that satisfies the task, step by 2


every 1 to 10 # no to, step is by 1 by default
every 1 to 10 # no by, step is 1 by default
every EXPR1 to EXPR2 by EXPR3 do EXPR4 # general case - EXPRn can be complete expressions including other generators such as to-by, every's do is optional
every EXPR1 to EXPR2 by EXPR3 do EXPR4 # general case - EXPRn can be complete expressions including other generators such as to-by, every's do is optional
steps := [2,3,5,7] # a list
steps := [2,3,5,7] # a list
Line 1,417: Line 1,560:


every writes( (TO_BY_EXPR) | "\n", " " ) # if you want to see how any of these work
every writes( (TO_BY_EXPR) | "\n", " " ) # if you want to see how any of these work
</syntaxhighlight>
</lang>
The ability to combine to-by arbitrarily is quite powerful.
The ability to combine to-by arbitrarily is quite powerful.
Yet it can lead to unexpected results. In cases of combined to-by operators the left associativity seems natural where the by is omitted.
Yet it can lead to unexpected results. In cases of combined to-by operators the left associativity seems natural where the by is omitted.
In cases where the by is used it might seem more natural to be right associative.
In cases where the by is used it might seem more natural to be right associative.
If in doubt parenthesize.
If in doubt parenthesize.

=={{Header|Insitux}}==

<syntaxhighlight lang="insitux">
(for i (range 0 10 2)
(print i)
(continue))

;or
(loop 5 i
(print (* i 2)))
</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang Io>for(i,2,8,2,
<syntaxhighlight lang="io">for(i,2,8,2,
write(i,", ")
write(i,", ")
)
)
write("who do we appreciate?")</lang>
write("who do we appreciate?")</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang J> ' who do we appreciate?' ,~ ": 2 * >: i.4
<syntaxhighlight lang="j"> ' who do we appreciate?' ,~ ": 2 * >: i.4
2 4 6 8 who do we appreciate?</lang>
2 4 6 8 who do we appreciate?</syntaxhighlight>

Note that an expression of the form <code>(start, step) (p. i.) count</code> will generate the specified numbers (<code>p.</code> is J's polynomial primitive, <code>i.</code> is J's index generator). So, to generate the above sequence of integers we could have used:

<syntaxhighlight lang=J> 0 2 (p. i.) 5
0 2 4 6 8</syntaxhighlight>


Or, using an actual for loop:
Or, using an "actual" for loop:


<lang J> 3 :0''
<syntaxhighlight lang="j"> 3 :0''
r=.$0
r=.$0
for_n. 2 * >: i.4 do.
for_n. 2 * >: i.4 do.
Line 1,442: Line 1,602:
' who do we appreciate?' ,~ ":n
' who do we appreciate?' ,~ ":n
)
)
2 4 6 8 who do we appreciate?</lang>
2 4 6 8 who do we appreciate?</syntaxhighlight>


That said, note also that J's '''steps''' verb lets us specify how many steps to take:
That said, note also that J's '''steps''' verb lets us specify how many steps to take:


<lang J> i:8
<syntaxhighlight lang="j"> i:8
_8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8
_8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8
i:8j8
i:8j8
_8 _6 _4 _2 0 2 4 6 8</lang>
_8 _6 _4 _2 0 2 4 6 8</syntaxhighlight>


Or, if we prefer, we could borrow the definition of <code>thru</code> from the [[Loops/Downward_for#J|Downward for]] task and then filter for the desired values:
Or, if we prefer, we could borrow the definition of <code>thru</code> from the [[Loops/Downward_for#J|Downward for]] task and then filter for the desired values:


<lang J> thru=: <./ + i.@(+*)@-~</lang>
<syntaxhighlight lang="j"> thru=: <./ + i.@(+*)@-~</syntaxhighlight>


Example use:
Example use:


<lang J> (#~ 0 = 2&|) 1 thru 20
<syntaxhighlight lang="j"> (#~ 0 = 2&|) 1 thru 20
2 4 6 8 10 12 14 16 18 20
2 4 6 8 10 12 14 16 18 20
(#~ 0 = 3&|) 1 thru 20
(#~ 0 = 3&|) 1 thru 20
3 6 9 12 15 18
3 6 9 12 15 18
(#~ 1 = 3&|) 1 thru 20
(#~ 1 = 3&|) 1 thru 20
1 4 7 10 13 16 19</lang>
1 4 7 10 13 16 19</syntaxhighlight>


And, of course, like filtering in any language, this approach supports non-constant step sizes:
And, of course, like filtering in any language, this approach supports non-constant step sizes, either by applying a function to each argument individually:


<lang J> (#~ 1&p:) 1 thru 20
<syntaxhighlight lang="j"> (#~ 1&p:) 1 thru 20
2 3 5 7 11 13 17 19</lang>
2 3 5 7 11 13 17 19</syntaxhighlight>

Or, by inserting a combining function between each value:

<syntaxhighlight lang="j"> (-&{.,])/ 1 thru 20
_10 11 _9 12 _8 13 _7 14 _6 15 _5 16 _4 17 _3 18 _2 19 _1 20</syntaxhighlight>

Other structural approaches can also be viable...


=={{header|Java}}==
=={{header|Java}}==
<lang java>for(int i = 2; i <= 8;i += 2){
<syntaxhighlight lang="java">for(int i = 2; i <= 8;i += 2){
System.out.print(i + ", ");
System.out.print(i + ", ");
}
}
System.out.println("who do we appreciate?");</lang>
System.out.println("who do we appreciate?");</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>var output = '',
<syntaxhighlight lang="javascript">var output = '',
i;
i;
for (i = 2; i <= 8; i += 2) {
for (i = 2; i <= 8; i += 2) {
Line 1,482: Line 1,649:
}
}
output += 'who do we appreciate?';
output += 'who do we appreciate?';
document.write(output);</lang>
document.write(output);</syntaxhighlight>


In a functional idiom of JavaScript, however, we will only be able to compose this computation within the superordinate expressions of our program if it has the the form of an expression returning a value, rather than that of a statement which fires off side-effects but returns no value.
In a functional idiom of JavaScript, however, we will only be able to compose this computation within the superordinate expressions of our program if it has the the form of an expression returning a value, rather than that of a statement which fires off side-effects but returns no value.
Line 1,488: Line 1,655:
Following the example of languages like Haskell and J on this page, we can begin by generating the stepped series as an expression. In functional JavaScript we will typically replace a state-changing loop with a non-mutating map or fold, writing, for example, something like:
Following the example of languages like Haskell and J on this page, we can begin by generating the stepped series as an expression. In functional JavaScript we will typically replace a state-changing loop with a non-mutating map or fold, writing, for example, something like:


<lang JavaScript>// range(iMax)
<syntaxhighlight lang="javascript">// range(iMax)
// range(iMin, iMax)
// range(iMin, iMax)
// range(iMin, iMax, dI)
// range(iMin, iMax, dI)
Line 1,508: Line 1,675:
console.log(
console.log(
range(2, 8, 2).join(', ') + ', who do we appreciate ?'
range(2, 8, 2).join(', ') + ', who do we appreciate ?'
);</lang>
);</syntaxhighlight>


Output:
Output:
Line 1,514: Line 1,681:


=={{header|jq}}==
=={{header|jq}}==
To generate the stream: 2,4,6,8:<lang jq># If your version of jq does not have range/3, use this:
To generate the stream: 2,4,6,8:<syntaxhighlight lang="jq"># If your version of jq does not have range/3, use this:
def range(m;n;step): range(0; ((n-m)/step) ) | m + (. * step);
def range(m;n;step): range(0; ((n-m)/step) ) | m + (. * step);


range(2;9;2)</lang>
range(2;9;2)</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>reduce range(2;9;2) as $i
<syntaxhighlight lang="jq">reduce range(2;9;2) as $i
(""; . + "\($i), ") +
(""; . + "\($i), ") +
"whom do we appreciate?"</lang>
"whom do we appreciate?"</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>for i in 2:2:8
<syntaxhighlight lang="julia">for i in 2:2:8
print(i, ", ")
print(i, ", ")
end
end
println("whom do we appreciate?")</lang>
println("whom do we appreciate?")</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
for (i in 1 .. 21 step 2) print("$i ")
for (i in 1 .. 21 step 2) print("$i ")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,545: Line 1,712:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def loops_for_with_a_specified_step
{def loops_for_with_a_specified_step
{lambda {:a :b :step}
{lambda {:a :b :step}
Line 1,560: Line 1,727:
{S.map {lambda {:i} :i} {S.serie 0 9 2}}
{S.map {lambda {:i} :i} {S.serie 0 9 2}}
-> 0 2 4 6 8
-> 0 2 4 6 8
</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: <range> over iota swap * rot + tuck swap <= select ; : tuck swap over ;
<syntaxhighlight lang="lang5">: <range> over iota swap * rot + tuck swap <= select ; : tuck swap over ;
: >>say.(*) . ;
: >>say.(*) . ;
1 10 2 <range> >>say.</lang>
1 10 2 <range> >>say.</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
<lang langur>for .i = 1; .i < 10; .i += 2 {
<syntaxhighlight lang="langur">for .i = 1; .i < 10; .i += 2 {
writeln .i
writeln .i
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,580: Line 1,747:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>loop(-to=100, -from=1, -by=2) => {^
<syntaxhighlight lang="lasso">loop(-to=100, -from=1, -by=2) => {^
loop_count
loop_count
'\r' // for formatting
'\r' // for formatting
^}</lang>
^}</syntaxhighlight>

=={{header|LDPL}}==
<syntaxhighlight lang="ldpl"># Display the even numbers up to twenty.

data:
i is number

procedure:
for i from 0 to 21 step 2 do
display i lf
repeat</syntaxhighlight>
{{out}}
<pre>
0
2
4
6
8
10
12
14
16
18
20
</pre>


=={{header|LIL}}==
=={{header|LIL}}==
The '''inc''' command accepts a value to add to the variable, 1 if not specified.
The '''inc''' command accepts a value to add to the variable, 1 if not specified.
<lang tcl>for {set i 1} {$i < 15} {inc i 3} {print $i}</lang>
<syntaxhighlight lang="tcl">for {set i 1} {$i < 15} {inc i 3} {print $i}</syntaxhighlight>
{{out}}
{{out}}
<pre># for {set i 1} {$i < 15} {inc i 3} {print $i}
<pre># for {set i 1} {$i < 15} {inc i 3} {print $i}
Line 1,599: Line 1,791:
=={{header|Lingo}}==
=={{header|Lingo}}==
Lingo loops don't support a "step" parameter, so it has to be implemented manually:
Lingo loops don't support a "step" parameter, so it has to be implemented manually:
<lang lingo>step = 3
<syntaxhighlight lang="lingo">step = 3
repeat with i = 0 to 10
repeat with i = 0 to 10
put i
put i
i = i + (step-1)
i = i + (step-1)
end repeat</lang>
end repeat</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,613: Line 1,805:


=={{header|Lisaac}}==
=={{header|Lisaac}}==
<lang Lisaac>1.to 9 by 2 do { i : INTEGER;
<syntaxhighlight lang="lisaac">1.to 9 by 2 do { i : INTEGER;
i.print;
i.print;
'\n'.print;
'\n'.print;
};</lang>
};</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>repeat with n = 0 to 10 step 2
<syntaxhighlight lang="livecode">repeat with n = 0 to 10 step 2
put n after loopn
put n after loopn
if n is not 10 then put comma after loopn
if n is not 10 then put comma after loopn
end repeat
end repeat
put loopn</lang>
put loopn</syntaxhighlight>
Output<lang LiveCode>0,2,4,6,8,10</lang>
Output<syntaxhighlight lang="livecode">0,2,4,6,8,10</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?]</lang>
<syntaxhighlight lang="logo">for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?]</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>
<syntaxhighlight lang="lua">
for i=2,9,2 do
for i=2,9,2 do
print(i)
print(i)
end
end
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,651: Line 1,843:
For this task we use single float numbers, and we make the loop one time from lower to higher value, and one time form higher to lower value.
For this task we use single float numbers, and we make the loop one time from lower to higher value, and one time form higher to lower value.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module LoopFor {
Module LoopFor {
Locale 1036
Locale 1036
Line 1,672: Line 1,864:
}
}
LoopFor
LoopFor
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,679: Line 1,871:
</pre>
</pre>
===Iterator step 2===
===Iterator step 2===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
a=("A", "B", "C", "D", "E", "F", "Z")
a=("A", "B", "C", "D", "E", "F", "Z")
k=Each(a)
k=Each(a)
Line 1,695: Line 1,887:
}
}
Print
Print
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,703: Line 1,895:


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`for',
<syntaxhighlight lang="m4">define(`for',
`ifelse($#,0,``$0'',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`ifelse(eval($2<=$3),1,
Line 1,710: Line 1,902:
for(`x',`1',`5',`3',`x
for(`x',`1',`5',`3',`x
')
')
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,719: Line 1,911:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>for i from 2 to 8 by 2 do
<syntaxhighlight lang="maple">for i from 2 to 8 by 2 do
i;
i;
end do;</lang>
end do;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,731: Line 1,923:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Do[
<lang Mathematica>Do[
Print[i],
Print[i],
{i, 1, 20, 4}]</lang>
{i, 1, 20, 4}]</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,743: Line 1,935:
=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<lang Matlab> for k = 0:10:100,
<syntaxhighlight lang="matlab"> for k = 0:10:100,
printf('%d\n',k)
printf('%d\n',k)
end; </lang>
end; </syntaxhighlight>


A vectorized version of the code is
A vectorized version of the code is


<lang Matlab> printf('%d\n',0:10:100); </lang>
<syntaxhighlight lang="matlab"> printf('%d\n',0:10:100); </syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>for i: 1 step 2 thru 10 do print(i);
<syntaxhighlight lang="maxima">for i: 1 step 2 thru 10 do print(i);
/* 1
/* 1
3
3
5
5
7 */</lang>
7 */</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang MAXScript>for i = 0 to 10 by 2 do format "%\n" i</lang>
<syntaxhighlight lang="maxscript">for i = 0 to 10 by 2 do format "%\n" i</syntaxhighlight>
Output:
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
0
0
2
2
Line 1,769: Line 1,961:
10
10
OK
OK
</syntaxhighlight>
</lang>


=={{header|min}}==
=={{header|min}}==
Printing the even numbers in <tt>[0,10)</tt>:
Printing the even numbers in <tt>[0,10)</tt>:
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>0 (dup 10 >=) 'pop (puts 2 +) () linrec</lang>
<syntaxhighlight lang="min">0 (dup 10 >=) 'pop (puts 2 +) () linrec</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>for i in range(1,20,4)
<syntaxhighlight lang="miniscript">for i in range(1,20,4)
print i
print i
end for</lang>
end for</syntaxhighlight>


{{out}}
{{out}}
Line 1,789: Line 1,981:


=={{header|МК-61/52}}==
=={{header|МК-61/52}}==
<lang>1 П0 ИП0 3 + П0 1 0 - x#0
<syntaxhighlight lang="text">1 П0 ИП0 3 + П0 1 0 - x#0
02 С/П</lang>
02 С/П</syntaxhighlight>


In this example, the step is 3, the lowest value is 1 and the upper limit is 10.
In this example, the step is 3, the lowest value is 1 and the upper limit is 10.


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE ForBy;
<syntaxhighlight lang="modula2">MODULE ForBy;
IMPORT InOut;
IMPORT InOut;


Line 1,806: Line 1,998:
InOut.WriteLn
InOut.WriteLn
END
END
END ForBy.</lang>
END ForBy.</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>FOR i := 1 TO 100 BY 2 DO
<syntaxhighlight lang="modula3">FOR i := 1 TO 100 BY 2 DO
IO.Put(Fmt.Int(i) & " ");
IO.Put(Fmt.Int(i) & " ");
END;</lang>
END;</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>FOR I=65:3:122 DO
<syntaxhighlight lang="mumps">FOR I=65:3:122 DO
.WRITE $CHAR(I)," "</lang>
.WRITE $CHAR(I)," "</syntaxhighlight>
{{out}}
{{out}}
<pre>A D G J M P S V Y \ _ b e h k n q t w z</pre>
<pre>A D G J M P S V Y \ _ b e h k n q t w z</pre>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>for (i = 2; i <= 8; i +=2)</lang>
<syntaxhighlight lang="nemerle">for (i = 2; i <= 8; i +=2)</syntaxhighlight>
<lang Nemerle>foreach (i in [2, 4 .. 8])</lang>
<syntaxhighlight lang="nemerle">foreach (i in [2, 4 .. 8])</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary


Line 1,833: Line 2,025:
say i_.format(3, 1) || '\0'
say i_.format(3, 1) || '\0'
end i_
end i_
say</lang>
say</syntaxhighlight>
{{out}}
{{out}}
<pre>D:\>java lst
<pre>D:\>java lst
Line 1,844: Line 2,036:
The increment step of the Never ''for'' expression can be simple or complex and need not be contiguous.
The increment step of the Never ''for'' expression can be simple or complex and need not be contiguous.


<lang fsharp>for (i = 0; i < 10; i += 3)</lang>
<syntaxhighlight lang="fsharp">for (i = 0; i < 10; i += 3)</syntaxhighlight>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(for (i 0 10 2)
<syntaxhighlight lang="newlisp">(for (i 0 10 2)
(println i))</lang>
(println i))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang="nim">
<lang nim>for x in countup(1, 10, 4): echo x</lang>

for n in 5 .. 9: # 5 to 9 (9-inclusive)
echo n

echo "" # spacer

for n in 5 ..< 9: # 5 to 9 (9-exclusive)
echo n

echo "" # spacer

for n in countup(0, 16, 4): # 0 to 16 step 4
echo n

echo "" # spacer

for n in countdown(16, 0, 4): # 16 to 0 step -4
echo n

</syntaxhighlight>
{{out}}
{{out}}
<pre>10
<pre>
1
5
5
6
9</pre>
7
8
9

5
6
7
8

0
4
8
12
16

16
12
8
4
0
</pre>

=={{header|N/t/roff}}==
Works with gnu nroff. Example from groff manual, with minimal modifications.
<syntaxhighlight lang="nroff">
.nr a 0 3
.while (\na < 19) \{\
\n+a
.\}
</syntaxhighlight>
{{out}}
<pre>3 6 9 12 15 18 21
</pre>

=={{header|Nu}}==
Here <code>each {}</code> is used to convert from a range to a list, so that it can be consumed by <code>every</code>
<syntaxhighlight lang="nu">
for i in (0..10 | each {} | every 2) {print $i}
</syntaxhighlight>
{{out}}
<pre>
0
2
4
6
8
10
</pre>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c Version 2
Works with oo2c Version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE LoopForStep;
MODULE LoopForStep;
IMPORT
IMPORT
Line 1,875: Line 2,134:
END
END
END LoopForStep.
END LoopForStep.
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,889: Line 2,148:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
for(i := 0; i < 10; i += 2;) {
for(i := 0; i < 10; i += 2;) {
i->PrintLine();
i->PrintLine();
};
};
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml># let for_step a b step fn =
<syntaxhighlight lang="ocaml"># let for_step a b step fn =
let rec aux i =
let rec aux i =
if i <= b then begin
if i <= b then begin
Line 1,913: Line 2,172:
6
6
8
8
- : unit = ()</lang>
- : unit = ()</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==
<lang octave>for i = 1:2:10
<syntaxhighlight lang="octave">for i = 1:2:10
disp(i)
disp(i)
endfor</lang>
endfor</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth> 1 100 2 step: i [ i println ]</lang>
<syntaxhighlight lang="oforth"> 1 100 2 step: i [ i println ]</syntaxhighlight>


=={{header|Openscad}}==
=={{header|Openscad}}==


<lang openscad>/* Loop from 3 to 9 in steps of 2 */
<syntaxhighlight lang="openscad">/* Loop from 3 to 9 in steps of 2 */


for ( l = [3:2:9] ) {
for ( l = [3:2:9] ) {
echo (l);
echo (l);
}
}
echo ("on a double white line.");</lang>
echo ("on a double white line.");</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>for I in 2..8;2 do
<syntaxhighlight lang="oz">for I in 2..8;2 do
{System.show I}
{System.show I}
end
end
{System.show done}
{System.show done}
</syntaxhighlight>
</lang>


=={{header|Panda}}==
=={{header|Panda}}==
Panda doesn't natively have a number generator with steps, so let's add it.
Panda doesn't natively have a number generator with steps, so let's add it.
<lang panda>fun for(from,to,step) type integer,integer,integer->integer
<syntaxhighlight lang="panda">fun for(from,to,step) type integer,integer,integer->integer
t=to.minus(from).divide(step)
t=to.minus(from).divide(step)
0..t.times(step).plus(from)
0..t.times(step).plus(from)
/test it for(1 6 2) -> 1 3 5
/test it for(1 6 2) -> 1 3 5


for(1 3 5)</lang>
for(1 3 5)</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>forstep(n=1,10,2,print(n))</lang>
<syntaxhighlight lang="parigp">forstep(n=1,10,2,print(n))</syntaxhighlight>


The <code>forstep</code> construct is actually more powerful.
The <code>forstep</code> construct is actually more powerful.
For example, to print numbers with last digit relatively prime to 10:
For example, to print numbers with last digit relatively prime to 10:
<lang parigp>forstep(n=1,100,[2,4,2,2],print(n))</lang>
<syntaxhighlight lang="parigp">forstep(n=1,100,[2,4,2,2],print(n))</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,960: Line 2,219:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>for($i=2; $i <= 8; $i += 2) {
<syntaxhighlight lang="perl">for($i=2; $i <= 8; $i += 2) {
print "$i, ";
print "$i, ";
}
}
print "who do we appreciate?\n";</lang>
print "who do we appreciate?\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{libheader|Phix/basics}}
{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">8</span> <span style="color: #008080;">by</span> <span style="color: #000000;">2</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d, "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d, "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"who do we appreciate?\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"who do we appreciate?\n"</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->

=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/For_with_a_specified_step
by Galileo, 11/2022 #/

include ..\Utilitys.pmt

( 2 8 2 ) for print ", " print endfor
"who do we appreciate?" print</syntaxhighlight>
{{out}}
<pre>2, 4, 6, 8, who do we appreciate?
=== Press any key to exit ===</pre>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php><?php
<syntaxhighlight lang="php"><?php
foreach (range(2, 8, 2) as $i)
foreach (range(2, 8, 2) as $i)
echo "$i, ";
echo "$i, ";
echo "who do we appreciate?\n";
echo "who do we appreciate?\n";
?></lang>
?></syntaxhighlight>
{{out}}
{{out}}
<pre>2, 4, 6, 8, who do we appreciate?</pre>
<pre>2, 4, 6, 8, who do we appreciate?</pre>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(for (N 1 (> 10 N) (+ N 2))
<syntaxhighlight lang="picolisp">(for (N 1 (> 10 N) (+ N 2))
(printsp N) )</lang>
(printsp N) )</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>int main() {
<syntaxhighlight lang="pike">int main() {
for(int i = 2; i <= 16; i=i+2) {
for(int i = 2; i <= 16; i=i+2) {
write(i + "\n");
write(i + "\n");
}
}
}</lang>
}</syntaxhighlight>


=={{header|PILOT}}==
=={{header|PILOT}}==
One of the advantages of needing to create loops manually by using conditional jumps is that a step of any integer is just as easy as a step of one.
One of the advantages of needing to create loops manually by using conditional jumps is that a step of any integer is just as easy as a step of one.
<lang pilot>R : Prints the odd numbers less than 10.
<syntaxhighlight lang="pilot">R : Prints the odd numbers less than 10.
C :i = 1
C :i = 1
*Loop
*Loop
Line 2,002: Line 2,273:
C :i = i + 2
C :i = i + 2
J ( i < 10 ) :*Loop
J ( i < 10 ) :*Loop
END:</lang>
END:</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
declare (n, i) fixed binary;
declare (n, i) fixed binary;


Line 2,012: Line 2,283:
put skip list (i);
put skip list (i);
end;
end;
</syntaxhighlight>
</lang>

=={{header|Plain English}}==
Plain English has only one type of loop: an infinite loop that can be given a conditional break or exit. So there is nothing particularly special about this.
<syntaxhighlight lang="plainenglish">
To run:
Start up.
Put 0 into a number.
Loop.
If the number is greater than 50, break.
Convert the number to a string.
Write the string to the console.
Add 5 to the number.
Repeat.
Wait for the escape key.
Shut down.</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>for ($i = 0; $i -lt 10; $i += 2) {
<syntaxhighlight lang="powershell">for ($i = 0; $i -lt 10; $i += 2) {
$i
$i
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
If you need a stepping iterator, write one:
If you need a stepping iterator, write one:
<lang prolog>for(Lo,Hi,Step,Lo) :- Step>0, Lo=<Hi.
<syntaxhighlight lang="prolog">for(Lo,Hi,Step,Lo) :- Step>0, Lo=<Hi.
for(Lo,Hi,Step,Val) :- Step>0, plus(Lo,Step,V), V=<Hi, !, for(V,Hi,Step,Val).
for(Lo,Hi,Step,Val) :- Step>0, plus(Lo,Step,V), V=<Hi, !, for(V,Hi,Step,Val).


example :-
example :-
for(0,10,2,Val), write(Val), write(' '), fail.
for(0,10,2,Val), write(Val), write(' '), fail.
example.</lang>
example.</syntaxhighlight>
<pre>?- example.
<pre>?- example.
0 2 4 6 8 10
0 2 4 6 8 10
true.</pre>
true.</pre>
Adding the following two rules lets you go backwards too:
Adding the following two rules lets you go backwards too:
<lang prolog>for(Hi,Lo,Step,Hi) :- Step<0, Lo=<Hi.
<syntaxhighlight lang="prolog">for(Hi,Lo,Step,Hi) :- Step<0, Lo=<Hi.
for(Hi,Lo,Step,Val) :- Step<0, plus(Hi,Step,V), Lo=<V, !, for(V,Lo,Step,Val).</lang>
for(Hi,Lo,Step,Val) :- Step<0, plus(Hi,Step,V), Lo=<V, !, for(V,Lo,Step,Val).</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.x}}
{{works with|Python|2.x}}
<lang python>for i in xrange(2, 9, 2):
<syntaxhighlight lang="python">for i in xrange(2, 9, 2):
print "%d," % i,
print "%d," % i,
print "who do we appreciate?"</lang>
print "who do we appreciate?"</syntaxhighlight>


{{works with|Python|3.x}}
{{works with|Python|3.x}}
<lang python>for i in range(2, 9, 2):
<syntaxhighlight lang="python">for i in range(2, 9, 2):
print("%d, " % i, end="")
print("%d, " % i, end="")
print("who do we appreciate?")</lang>
print("who do we appreciate?")</syntaxhighlight>


{{out}}
{{out}}
Line 2,052: Line 2,338:
The step size is specified within the loop, giving many possibilities.
The step size is specified within the loop, giving many possibilities.


<syntaxhighlight lang="quackery">
<lang Quackery>
20 times [ i^ echo sp
20 times [ i^ echo sp
2 step ]
2 step ]
Line 2,061: Line 2,347:
1 56 times [ i^ echo sp
1 56 times [ i^ echo sp
i^ swap step ]
i^ swap step ]
cr</lang>
cr</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,071: Line 2,357:


=={{header|R}}==
=={{header|R}}==
<lang R>for(a in seq(2,8,2)) {
<syntaxhighlight lang="r">for(a in seq(2,8,2)) {
cat(a, ", ")
cat(a, ", ")
}
}
cat("who do we appreciate?\n")</lang>
cat("who do we appreciate?\n")</syntaxhighlight>


Here the loop may be done implicitly by first concatenating the string and then printing:
Here the loop may be done implicitly by first concatenating the string and then printing:


<lang R>cat(paste(c(seq(2, 8, by=2), "who do we appreciate?\n"), collapse=", "))</lang>
<syntaxhighlight lang="r">cat(paste(c(seq(2, 8, by=2), "who do we appreciate?\n"), collapse=", "))</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 2,088: Line 2,374:
(printf "~a, " i))
(printf "~a, " i))
(printf "who do we appreciate?~n")
(printf "who do we appreciate?~n")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,116: Line 2,402:
Probably the most straightforward way to do this is with a sequence. With at least two values on the left-hand side, the sequence operator (<code>...</code>) can infer an arithmetic series. (With at least three values, it can infer a geometric sequence, too.)
Probably the most straightforward way to do this is with a sequence. With at least two values on the left-hand side, the sequence operator (<code>...</code>) can infer an arithmetic series. (With at least three values, it can infer a geometric sequence, too.)


<lang perl6>for 2, 4 ... 8 {
<syntaxhighlight lang="raku" line>for 2, 4 ... 8 {
print "$_, ";
print "$_, ";
}
}
say 'whom do we appreciate?';</lang><!-- "Whom" is infinitely more amusing. -->
say 'whom do we appreciate?';</syntaxhighlight><!-- "Whom" is infinitely more amusing. -->


But there is nothing constraining the sequence to a constant step. Here's one with a ''random'' step.
But there is nothing constraining the sequence to a constant step. Here's one with a ''random'' step.


<lang perl6>.say for rand, *+rand-.5 ... *.abs>2</lang>
<syntaxhighlight lang="raku" line>.say for rand, *+rand-.5 ... *.abs>2</syntaxhighlight>


{{out|Sample output}}
{{out|Sample output}}
Line 2,146: Line 2,432:
For that matter, the iterated object doesn't need to contain numbers.
For that matter, the iterated object doesn't need to contain numbers.


<lang perl6>.say for <17/32 π banana 👀 :d(7) 🦋>;</lang>
<syntaxhighlight lang="raku" line>.say for <17/32 π banana 👀 :d(7) 🦋>;</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
List of numbers:
List of numbers:
<lang Raven>[ 2 4 6 8 ] each "%d, " print
<syntaxhighlight lang="raven">[ 2 4 6 8 ] each "%d, " print
"who do we appreciate?\n" print</lang>
"who do we appreciate?\n" print</syntaxhighlight>


Range:
Range:
<lang Raven>2 10 2 range each "%d, " print
<syntaxhighlight lang="raven">2 10 2 range each "%d, " print
"who do we appreciate?\n" print</lang>
"who do we appreciate?\n" print</syntaxhighlight>
{{out}}
{{out}}
<pre>2, 4, 6, 8, who do we appreciate?
<pre>2, 4, 6, 8, who do we appreciate?
Line 2,161: Line 2,447:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>for i 2 8 2 [
<syntaxhighlight lang="rebol">for i 2 8 2 [
prin rejoin [i ", "]]
prin rejoin [i ", "]]
print "who do we appreciate?"</lang>
print "who do we appreciate?"</syntaxhighlight>


{{out}}
{{out}}
Line 2,170: Line 2,456:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx> do x=1 to 10 by 1.5
<syntaxhighlight lang="rexx"> do x=1 to 10 by 1.5
say x
say x
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,185: Line 2,471:


===version 2===
===version 2===
<lang rexx> do thing=1 by 3/2 to 10
<syntaxhighlight lang="rexx"> do thing=1 by 3/2 to 10
say thing
say thing
end</lang>
end</syntaxhighlight>
'''output''' is the same as above.
'''output''' is the same as above.
<br><br>
<br><br>


===version 3===
===version 3===
<lang rexx>Do v=1 by 3/2 While v**2<30
<syntaxhighlight lang="rexx">Do v=1 by 3/2 While v**2<30
Say v
Say v
End
End
Say '('v'**2) is greater than 30 (30.25)'</lang>
Say '('v'**2) is greater than 30 (30.25)'</syntaxhighlight>
{{output}}
{{output}}
<pre>1
<pre>1
Line 2,205: Line 2,491:
we use step keyword to define step length
we use step keyword to define step length
in this example we print Even numbers between 0 and 10
in this example we print Even numbers between 0 and 10
<lang ring>
<syntaxhighlight lang="ring">
for i = 0 to 10 step 2 see i + nl next
for i = 0 to 10 step 2 see i + nl next
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,219: Line 2,505:


we can use step with double values as well:
we can use step with double values as well:
<lang ring>
<syntaxhighlight lang="ring">
for i = 0 to 10 step 0.5 see i + nl next
for i = 0 to 10 step 0.5 see i + nl next
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,247: Line 2,533:
</pre>
</pre>


=={{header|RPL}}==
Specific increment is given as an argument to the <code>STEP</code> instruction at the end of each loop. Usually, it is a constant value, but it could be a variable if it makes sense.
≪ 1 10 '''FOR''' j
j
2 '''STEP'''
=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>2.step(8,2) {|n| print "#{n}, "}
<syntaxhighlight lang="ruby">2.step(8,2) {|n| print "#{n}, "}
puts "who do we appreciate?"</lang>
puts "who do we appreciate?"</syntaxhighlight>
or:
or:
<lang ruby>(2..8).step(2) {|n| print "#{n}, "}
<syntaxhighlight lang="ruby">(2..8).step(2) {|n| print "#{n}, "}
puts "who do we appreciate?"</lang>
puts "who do we appreciate?"</syntaxhighlight>
or:
or:
<lang ruby>for n in (2..8).step(2)
<syntaxhighlight lang="ruby">for n in (2..8).step(2)
print "#{n}, "
print "#{n}, "
end
end
puts "who do we appreciate?"</lang>
puts "who do we appreciate?"</syntaxhighlight>
or:
<syntaxhighlight lang="ruby">for n in 2.step(by: 2, to: 8)
print "#{n}, "
end
puts "who do we appreciate?"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,266: Line 2,563:


For Rust 1.28 and later:
For Rust 1.28 and later:
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
for i in (2..=8).step_by(2) {
for i in (2..=8).step_by(2) {
print!("{}", i);
print!("{}", i);
}
}
println!("who do we appreciate?!");
println!("who do we appreciate?!");
}</lang>
}</syntaxhighlight>


An alternative which also works in earlier versions of Rust:
An alternative which also works in earlier versions of Rust:
<lang rust>fn main() {
<syntaxhighlight lang="rust">fn main() {
let mut i = 2;
let mut i = 2;
while i <= 8 {
while i <= 8 {
Line 2,281: Line 2,578:
}
}
println!("who do we appreciate?!");
println!("who do we appreciate?!");
}</lang>
}</syntaxhighlight>


=={{header|Salmon}}==
=={{header|Salmon}}==
<lang Salmon>for (x; 2; x <= 8; 2)
<syntaxhighlight lang="salmon">for (x; 2; x <= 8; 2)
print(x, ", ");;
print(x, ", ");;
print("who do we appreciate?\n");</lang>
print("who do we appreciate?\n");</syntaxhighlight>


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>data _null_;
<syntaxhighlight lang="sas">data _null_;
do i=1 to 10 by 2;
do i=1 to 10 by 2;
put i;
put i;
end;
end;
run;</lang>
run;</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
See [[Loops/For#Sather]]: the implementation for <code>for!</code> allows to specify a step, even though the built-in <code>stepto!</code> can be used; an example of usage could be simply:
See [[Loops/For#Sather]]: the implementation for <code>for!</code> allows to specify a step, even though the built-in <code>stepto!</code> can be used; an example of usage could be simply:
<lang sather> i :INT;
<syntaxhighlight lang="sather"> i :INT;
loop
loop
i := for!(1, 50, 2);
i := for!(1, 50, 2);
Line 2,303: Line 2,600:
-- i := 1.stepto!(50, 2);
-- i := 1.stepto!(50, 2);
#OUT + i + "\n";
#OUT + i + "\n";
end;</lang>
end;</syntaxhighlight>


(Print all odd numbers from 1 to 50)
(Print all odd numbers from 1 to 50)


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>for (i <- 2 to 8 by 2) println(i)</lang>
<syntaxhighlight lang="scala">for (i <- 2 to 8 by 2) println(i)</syntaxhighlight>


Alternatively:
Alternatively:
<lang scala>(2 to 8 by 2) foreach println</lang>
<syntaxhighlight lang="scala">(2 to 8 by 2) foreach println</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
The built-in ''for''-like form in Scheme is the ''do'' form:
The built-in ''for''-like form in Scheme is the ''do'' form:


<lang scheme>(do ((i 2 (+ i 2))) ; list of variables, initials and steps -- you can iterate over several at once
<syntaxhighlight lang="scheme">(do ((i 2 (+ i 2))) ; list of variables, initials and steps -- you can iterate over several at once
((>= i 9)) ; exit condition
((>= i 9)) ; exit condition
(display i) ; body
(display i) ; body
(newline))</lang>
(newline))</syntaxhighlight>


Some people prefer to use the recursive-style and more flexible _named let_ form:
Some people prefer to use the recursive-style and more flexible _named let_ form:


<lang scheme>(let loop ((i 2)) ; function name, parameters and starting values
<syntaxhighlight lang="scheme">(let loop ((i 2)) ; function name, parameters and starting values
(cond ((< i 9)
(cond ((< i 9)
(display i)
(display i)
(newline)
(newline)
(loop (+ i 2)))))) ; tail-recursive call, won't create a new stack frame</lang>
(loop (+ i 2)))))) ; tail-recursive call, won't create a new stack frame</syntaxhighlight>


You can add to the language by wrapping the loop in a function:
You can add to the language by wrapping the loop in a function:


<lang scheme>(define (for-loop start end step func)
<syntaxhighlight lang="scheme">(define (for-loop start end step func)
(let loop ((i start))
(let loop ((i start))
(cond ((< i end)
(cond ((< i end)
Line 2,340: Line 2,637:
(lambda (i)
(lambda (i)
(display i)
(display i)
(newline)))</lang>
(newline)))</syntaxhighlight>


... or in a macro, which allows for making the <code>(lambda)</code> implicit:
... or in a macro, which allows for making the <code>(lambda)</code> implicit:


<lang scheme>(define-syntax for-loop
<syntaxhighlight lang="scheme">(define-syntax for-loop
(syntax-rules ()
(syntax-rules ()
((for-loop index start end step body ...)
((for-loop index start end step body ...)
Line 2,354: Line 2,651:
(for-loop i 2 9 2
(for-loop i 2 9 2
(display i)
(display i)
(newline))</lang>
(newline))</syntaxhighlight>


{{out}}
{{out}}
Line 2,364: Line 2,661:
=={{header|Scilab}}==
=={{header|Scilab}}==
{{works with|Scilab|5.5.1}}
{{works with|Scilab|5.5.1}}
<lang>for i=1:2:10
<syntaxhighlight lang="text">for i=1:2:10
printf("%d\n",i)
printf("%d\n",i)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 2,375: Line 2,672:


=={{header|Seed7}}==
=={{header|Seed7}}==
<syntaxhighlight lang="python">
<lang seed7>$ include "seed7_05.s7i";
$ include "seed7_05.s7i";


const proc: main is func
const proc: main is func
Line 2,381: Line 2,679:
var integer: number is 0;
var integer: number is 0;
begin
begin
for number range 1 to 10 step 2 do
for number range 0 to 10 step 2 do # 10 is inclusive
writeln(number);
writeln(number);
end for;
end for;

end func;</lang>
writeln; # spacer
for number range 10 downto 0 step 2 do
writeln(number);
end for;
end func;

</syntaxhighlight>
{{out}}
<pre>
0
2
4
6
8
10

10
8
6
4
2
0
</pre>


=={{header|Sidef}}==
=={{header|Sidef}}==


'''for(;;)''' loop:
'''for(;;)''' loop:
<lang ruby>for (var i = 2; i <= 8; i += 2) {
<syntaxhighlight lang="ruby">for (var i = 2; i <= 8; i += 2) {
say i
say i
}</lang>
}</syntaxhighlight>


'''for-in''' loop:
'''for-in''' loop:
<lang ruby>for i in (2 .. (8, 2)) {
<syntaxhighlight lang="ruby">for i in (2 .. (8, 2)) {
say i
say i
}</lang>
}</syntaxhighlight>


'''.each''' method:
'''.each''' method:
<lang ruby>2.to(8).by(2).each { |i|
<syntaxhighlight lang="ruby">2.to(8).by(2).each { |i|
say i
say i
}</lang>
}</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>begin
<syntaxhighlight lang="simula">begin
integer i;
integer i;
for i:=5 step 5 until 25 do outint(i, 5)
for i:=5 step 5 until 25 do outint(i, 5)
end</lang>
end</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>2 to: 8 by: 2 do: [| :i | Console ; i printString ; ', '].
<syntaxhighlight lang="slate">2 to: 8 by: 2 do: [| :i | Console ; i printString ; ', '].
inform: 'enough with the cheering already!'.</lang>
inform: 'enough with the cheering already!'.</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>2 to: 8 by: 2 do: [ :i |
<syntaxhighlight lang="smalltalk">2 to: 8 by: 2 do: [ :i |
Transcript show: i; show ', '
Transcript show: i; show ', '
].
].
Transcript showCr: 'enough with the cheering already!'</lang>
Transcript showCr: 'enough with the cheering already!'</syntaxhighlight>


=={{header|Spin}}==
=={{header|Spin}}==
Line 2,424: Line 2,747:
{{works with|HomeSpun}}
{{works with|HomeSpun}}
{{works with|OpenSpin}}
{{works with|OpenSpin}}
<lang spin>con
<syntaxhighlight lang="spin">con
_clkmode = xtal1 + pll16x
_clkmode = xtal1 + pll16x
_clkfreq = 80_000_000
_clkfreq = 80_000_000
Line 2,440: Line 2,763:
waitcnt(_clkfreq + cnt)
waitcnt(_clkfreq + cnt)
ser.stop
ser.stop
cogstop(0)</lang>
cogstop(0)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,447: Line 2,770:


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>> n, 1..10,2
<syntaxhighlight lang="spl">> n, 1..10,2
#.output(n)
#.output(n)
<</lang>
<</syntaxhighlight>


=={{header|SSEM}}==
=={{header|SSEM}}==
Implementing loops with a step other than one is precisely as easy (or as fiddly) as implementing loops with a step equal to one. This example program uses a loop to perform integer division. It should be run with the dividend in storage location 21 and the divisor in storage location 22. To show that it works, we shall ask the machine to count from 387 in steps of -5 and to halt with the accumulator showing the number of times it has done so before producing a negative result.
Implementing loops with a step other than one is precisely as easy (or as fiddly) as implementing loops with a step equal to one. This example program uses a loop to perform integer division. It should be run with the dividend in storage location 21 and the divisor in storage location 22. To show that it works, we shall ask the machine to count from 387 in steps of -5 and to halt with the accumulator showing the number of times it has done so before producing a negative result.
<lang ssem>10101000000000100000000000000000 0. -21 to c
<syntaxhighlight lang="ssem">10101000000000100000000000000000 0. -21 to c
00101000000001100000000000000000 1. c to 20
00101000000001100000000000000000 1. c to 20
00101000000000100000000000000000 2. -20 to c
00101000000000100000000000000000 2. -20 to c
Line 2,477: Line 2,800:
10100000000000000000000000000000 22. 5
10100000000000000000000000000000 22. 5
00000000000000000000000000000000 23. 0
00000000000000000000000000000000 23. 0
10110000000000000000000000000000 24. 13</lang>
10110000000000000000000000000000 24. 13</syntaxhighlight>
After executing 1,012 instructions, the computer halts with the correct quotient—77—in the accumulator.
After executing 1,012 instructions, the computer halts with the correct quotient—77—in the accumulator.


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>forvalues i=1(2)10 {
<syntaxhighlight lang="stata">forvalues i=1(2)10 {
display "`i'"
display "`i'"
}
}
Line 2,489: Line 2,812:
5
5
7
7
9</lang>
9</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
This prints all odd digits:
This prints all odd digits:
<lang swift>for i in stride(from: 1, to: 10, by: 2) {
<syntaxhighlight lang="swift">for i in stride(from: 1, to: 10, by: 2) {
print(i)
print(i)
}</lang>
}</syntaxhighlight>
Alternately (removed in Swift 3):
Alternately (removed in Swift 3):
<lang swift>for var i = 1; i < 10; i += 2 {
<syntaxhighlight lang="swift">for var i = 1; i < 10; i += 2 {
print(i)
print(i)
}</lang>
}</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
Tailspin uses streams not loops
Tailspin uses streams not loops
<lang tailspin>
<syntaxhighlight lang="tailspin">
1..9:3 -> !OUT::write
1..9:3 -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,512: Line 2,835:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>for {set i 2} {$i <= 8} {incr i 2} {
<syntaxhighlight lang="tcl">for {set i 2} {$i <= 8} {incr i 2} {
puts -nonewline "$i, "
puts -nonewline "$i, "
}
}
puts "enough with the cheering already!"</lang>
puts "enough with the cheering already!"</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==


<lang TorqueScript>for(%i = 0; %i < 201; %i += 2)
<syntaxhighlight lang="torquescript">for(%i = 0; %i < 201; %i += 2)
{
{
echo(%i);
echo(%i);
}</lang>
}</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
LOOP i=2,9,2
LOOP i=2,9,2
PRINT i
PRINT i
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,543: Line 2,866:
==={{header|Bourne Shell}}===
==={{header|Bourne Shell}}===
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>x=2
<syntaxhighlight lang="bash">x=2
while test $x -le 8; do
while test $x -le 8; do
echo $x
echo $x
x=`expr $x + 2` || exit $?
x=`expr $x + 2` || exit $?
done</lang>
done</syntaxhighlight>
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
{{libheader|jot}}
{{libheader|jot}}
<lang bash>for x in `jot - 2 8 2`; do echo $x; done</lang>
<syntaxhighlight lang="bash">for x in `jot - 2 8 2`; do echo $x; done</syntaxhighlight>


==={{header|Korn Shell}}===
==={{header|ksh}}===
<syntaxhighlight lang="ksh">x=0
{{works with|Korn Shell}}
while (((x += 2) <= 8))
<lang bash>x=2
do
while [[$x -le 8]]; do
print -r "$x"
echo $x
done</syntaxhighlight>
((x=x+2))
{{works with|ksh93}}
done</lang>
<syntaxhighlight lang="ksh">for x in {2..8..2}
{{works with|Korn Shell}}
do
<lang bash>x=2
print -r "$x"
while ((x<=8)); do
done</syntaxhighlight>
echo $x
((x+=2))
done</lang>


===Bourne Again Shell===
===Bourne Again Shell===
{{works with|Bourne Again SHell|3}}
{{works with|Bourne Again SHell|3}}
<lang bash>for (( x=2; $x<=8; x=$x+2 )); do
<syntaxhighlight lang="bash">for (( x=2; $x<=8; x=$x+2 )); do
printf "%d, " $x
printf "%d, " $x
done</lang>
done</syntaxhighlight>


{{works with|Bourne Again SHell|4}}
{{works with|Bourne Again SHell|4}}
Bash v4.0+ has inbuilt support for setting up a step value
Bash v4.0+ has inbuilt support for setting up a step value
<lang bash>for x in {2..8..2}
<syntaxhighlight lang="bash">for x in {2..8..2}
do
do
echo $x
echo $x
done</lang>
done</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
{{libheader|jot}}
{{libheader|jot}}
<lang csh>foreach x (`jot - 2 8 2`)
<syntaxhighlight lang="csh">foreach x (`jot - 2 8 2`)
echo $x
echo $x
end</lang>
end</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
{{trans|Python}}
{{trans|Python}}
<lang ursa>decl int i
<syntaxhighlight lang="ursa">decl int i
for (set i 2) (< i 9) (set i (int (+ i 2)))
for (set i 2) (< i 9) (set i (int (+ i 2)))
out i ", " console
out i ", " console
end for
end for
out "who do we appreciate?" endl console</lang>
out "who do we appreciate?" endl console</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>for (int i = 1; i < 10; i += 2)
<syntaxhighlight lang="vala">for (int i = 1; i < 10; i += 2)
stdout.printf("%d\n", i);</lang>
stdout.printf("%d\n", i);</syntaxhighlight>


=={{header|VAX Assembly}}==
=={{header|VAX Assembly}}==
<lang VAX Assembly> 0000 0000 1 .entry main,0
<syntaxhighlight lang="vax assembly"> 0000 0000 1 .entry main,0
50 D4 0002 2 clrf r0 ;init to 0.0
50 D4 0002 2 clrf r0 ;init to 0.0
0004 3 loop:
0004 3 loop:
Line 2,605: Line 2,926:
000B 6
000B 6
04 000B 7 ret
04 000B 7 ret
000C 8 .end main</lang>
000C 8 .end main</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Sub MyLoop()
<syntaxhighlight lang="vb">Sub MyLoop()
For i = 2 To 8 Step 2
For i = 2 To 8 Step 2
Debug.Print i;
Debug.Print i;
Next i
Next i
Debug.Print
Debug.Print
End Sub</lang>
End Sub</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,620: Line 2,941:


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>buffer = ""
<syntaxhighlight lang="vb">buffer = ""
For i = 2 To 8 Step 2
For i = 2 To 8 Step 2
buffer = buffer & i & " "
buffer = buffer & i & " "
Next
Next
WScript.Echo buffer</lang>
WScript.Echo buffer</syntaxhighlight>
{{out}}
{{out}}
<pre>2 4 6 8</pre>
<pre>2 4 6 8</pre>
Line 2,630: Line 2,951:
=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
This prints all odd digits in range 1 to 9:
This prints all odd digits in range 1 to 9:
<lang vedit>for (#1 = 1; #1 < 10; #1 += 2) {
<syntaxhighlight lang="vedit">for (#1 = 1; #1 < 10; #1 += 2) {
Num_Type(#1)
Num_Type(#1)
}</lang>
}</syntaxhighlight>




=={{header|Verilog}}==
=={{header|Verilog}}==
Imprime todos los números impares
Imprime todos los números impares
<syntaxhighlight lang="verilog">
<lang Verilog>
module main;
module main;
integer i;
integer i;
Line 2,647: Line 2,968:
end
end
endmodule
endmodule
</syntaxhighlight>
</lang>




=={{header|Vim Script}}==
=={{header|Vim Script}}==
<lang vim>for i in range(2, 10, 2)
<syntaxhighlight lang="vim">for i in range(2, 10, 2)
echo i
echo i
endfor</lang>
endfor</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,661: Line 2,982:
8
8
10</pre>
10</pre>

=={{header|V (Vlang)}}==
This prints all odd digits:
<syntaxhighlight lang="v (vlang)">for i := 1; i<10; i+=2 {
println(i)
}</syntaxhighlight>


=={{header|Vorpal}}==
=={{header|Vorpal}}==
<lang vorpal>for(i = 2, i <= 8, i = i + 2){
<syntaxhighlight lang="vorpal">for(i = 2, i <= 8, i = i + 2){
i.print()
i.print()
}</lang>
}</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>for i 2 (i <= 8) (i <- i+2)
<syntaxhighlight lang="wart">for i 2 (i <= 8) (i <- i+2)
prn i</lang>
prn i</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
There is currently no direct way to incorporate a step into a ''for'' loop but we can simulate it by declaring a second variable at the start of the loop which maps the loop variable to the value we want or we can simply use a ''while'' loop instead.
There is currently no direct way to incorporate a step into a ''for'' loop but we can simulate it by declaring a second variable at the start of the loop which maps the loop variable to the value we want or we can simply use a ''while'' loop instead.
<lang ecmascript>// Print odd numbers under 20.
<syntaxhighlight lang="wren">// Print odd numbers under 20.
for (i in 1..10) {
for (i in 1..10) {
var j = 2*i - 1
var j = 2*i - 1
Line 2,687: Line 3,014:
k = k + 2
k = k + 2
}
}
System.print()</lang>
System.print()</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,695: Line 3,022:
</pre>
</pre>
<br>
<br>
{{libheader|Wren-trait}}
{{libheader|Wren-iterate}}
A further and more general approach is to use a wrapper class (such as the one in the above module) which can iterate over any sequence in a stepped fashion using Wren's ''iterator protocol''.
A further and more general approach is to use a wrapper class (such as the one in the above module) which can iterate over any sequence in a stepped fashion using Wren's ''iterator protocol''.
<lang ecmascript>import "/trait" for Stepped
<syntaxhighlight lang="wren">import "./iterate" for Stepped


// Print odd numbers under 20.
// Print odd numbers under 20.
Line 2,705: Line 3,032:
// Print first plus every third element thereafter.
// Print first plus every third element thereafter.
for (i in Stepped.new(1..20, 3)) System.write("%(i) ")
for (i in Stepped.new(1..20, 3)) System.write("%(i) ")
System.print()</lang>
System.print()</syntaxhighlight>


{{out}}
{{out}}
Line 2,718: Line 3,045:
thus a step by 2 can be implemented like this:
thus a step by 2 can be implemented like this:


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int I;
int I;
[for I:= 2 to 8 do
[for I:= 2 to 8 do
Line 2,725: Line 3,052:
];
];
Text(0, "who do we appreciate?");
Text(0, "who do we appreciate?");
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,733: Line 3,060:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>foreach n in ([1..10,4]) {println(n)}
<syntaxhighlight lang="zkl">foreach n in ([1..10,4]) {println(n)}
[1..10,3].pump(Console.println)</lang>
[1..10,3].pump(Console.println)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,747: Line 3,074:
</pre>
</pre>
A few others:
A few others:
<lang zkl>fcn loop(i=0){println(i); if(i<10)return(self.fcn(i+2))}
<syntaxhighlight lang="zkl">fcn loop(i=0){println(i); if(i<10)return(self.fcn(i+2))}
(0).pump(10,Console.println,fcn(n){if(n%2)return(Void.Skip); n})</lang>
(0).pump(10,Console.println,fcn(n){if(n%2)return(Void.Skip); n})</syntaxhighlight>


{{omit from|GUISS}}
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");

pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
var i: u8 = 1;
while (i < 10) : (i += 2)
try stdout_wr.print("{d}\n", .{i});
}
</syntaxhighlight>

===With for-loop===
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = @import("std").io.getStdOut().writer();

pub fn main() !void {
for (1..10) |n| {
if (n % 2 == 0) continue;
try stdout.print("{d}\n", .{n});
}
}
</syntaxhighlight>
{{out}}
<pre>
1
3
5
7
9
</pre>

Latest revision as of 07:56, 15 April 2024

Task
Loops/For with a specified step
You are encouraged to solve this task according to the task description, using any language you may know.


Task

Demonstrate a   for-loop   where the step-value is greater than one.


Related tasks



11l

L(i) (1..9).step(2)
   print(i)
Output:
1
3
5
7
9

360 Assembly

Basic - Algol style

The opcode BXH uses 3 registers, one for index one for step and one for limit.

*        Loops/For with a specified step     12/08/2015
LOOPFORS CSECT
         USING  LOOPFORS,R12
         LR     R12,R15
*     == Algol style ================ test at the beginning
         LA     R3,BUF             idx=0
         LA     R5,0               from 5 (from-step=0)
         LA     R6,5               step 5
         LA     R7,25              to 25
LOOPI    BXH    R5,R6,ELOOPI       for i=5 to 25 step 5
         XDECO  R5,XDEC              edit i
         MVC    0(4,R3),XDEC+8       output i
         LA     R3,4(R3)             idx=idx+4
         B      LOOPI              next i
ELOOPI   XPRNT  BUF,80             print buffer
         BR     R14
BUF      DC     CL80' '            buffer
XDEC     DS     CL12               temp for edit
         YREGS  
         END    LOOPFORS
Output:
   5  10  15  20  25
Basic - Fortran style

The opcode BXLE uses 3 registers, one for index one for step and one for limit.

*     == Fortran style ============== test at the end
         LA     R3,BUF             idx=0
         LA     R5,5               from 5
         LA     R6,5               step 5
         LA     R7,25              to 25
LOOPJ    XDECO  R5,XDEC            for j=5 to 25 step 5;  edit j
         MVC    0(4,R3),XDEC+8       output j
         LA     R3,4(R3)             idx=idx+4
         BXLE   R5,R6,LOOPJ        next j
         XPRNT  BUF,80             print buffer
Structured Macros
*     == Algol style ================ test at the beginning
         LA     R3,BUF             idx=0
         LA     R5,5               from 5 
         LA     R6,5               step 5
         LA     R7,25              to 25
         DO WHILE=(CR,R5,LE,R7)    for i=5 to 25 step 5
           XDECO  R5,XDEC            edit i 
           MVC    0(4,R3),XDEC+8     output i
           LA     R3,4(R3)           idx=idx+4
           AR     R5,R6              i=i+step
         ENDDO  ,                  next i
         XPRNT  BUF,80             print buffer
Structured Macros HLASM
*     == Fortran style ============== test at the end
         LA     R3,BUF             idx=0
         DO FROM=(R5,5),TO=(R7,25),BY=(R6,5)  for i=5 to 25 step 5
           XDECO  R5,XDEC            edit i 
           MVC    0(4,R3),XDEC+8     output i
           LA     R3,4(R3)           idx=idx+4
         ENDDO  ,                  next i
         XPRNT  BUF,80             print buffer

6502 Assembly

This loop loads from an array and writes each element to memory addresses $D000, $D002, $D004, $D006, $D008, $D00A, $D00C, $D00E, in ascending order.

define ArrayPointerLo $00   ;define some helpful labels.
define ArrayPointerHi $01
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
setArray:      ;Easy6502 doesn't let us define arbitrary bytes so the best option is to fill the range at runtime.
lda #$10
ldx #0
loop_setArray:
sta $1200,x
clc
adc #$10
inx
cpx #$08
bcc loop_setArray
; stores this sequence of hex values starting at $1200: $10 $20 $30 $40 $50 $60 $70 $80

ClearMem:      ;clear $D000-$D0FF
lda #0
ldx #0
loop_clearMem:
sta $D000,x
inx
bne loop_clearMem
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; end of prep work, the real code begins here.

lda #$12              ;high byte of array address
sta ArrayPointerHi
lda #$00              ;low byte of array address
sta ArrayPointerLo    ;these are used to look up the array rather than hard-code it in.



ldx #$0E              ;the loop counter, gets decremented twice per iteration to skip the odd addresses.
ldy #7                ;the index into the source array.

;on the 6502 looping backwards is almost always faster.

loop_fill:
lda (ArrayPointerLo),y ;loads from the array's base address, plus Y
sta $D000,x            ;store at $D000+X
dey                    ;decrement array index
dex 
dex                    ;decrement destination index twice
bpl loop_fill          ;if destination index equals #$FF, we are done.

brk                    ;end of program
Output:
d000: 10 00 20 00 30 00 40 00 50 00 60 00 70 00 80 00

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program loopstep64.s   */
 
/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ MAXI,   20
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:  .asciz "Counter =  @ \n"      // message result

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss 
sZoneConv:             .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                           // entry of program 
    mov x4,0                    // init counter
1:                              // begin loop 
    mov x0,x4
    ldr x1,qAdrsZoneConv        // display value
    bl conversion10             // call function with 2 parameter (x0,x1)
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv   
    bl strInsertAtCharInc       // insert result at first @ character
    bl affichageMess            // display message
    add x4,x4,2                 // increment counter by 2
    cmp x4,MAXI                 //
    ble 1b                      // loop
 
100:                            // standard end of the program 
    mov x0,0                    // return code
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
 
qAdrsZoneConv:            .quad sZoneConv
qAdrszMessResult:         .quad szMessResult
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"

Action!

PROC Main()
  BYTE i

  FOR i=0 TO 70 STEP 7
  DO
    PrintF("%B ",i)
  OD
RETURN
Output:

Screenshot from Atari 8-bit computer

0 7 14 21 28 35 42 49 56 63 70

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, a valid range must always be provided before entering a loop. Because exact adherence to the task is impossible, we have three versions to approximate a solution. Looper_1 goes through a range of values which are even. Looper_2 multiples each value by two. Looper_3 most closely adheres to the requirements of this task, and achieves this by using a second range for the indices.

with Loopers;
use Loopers;


procedure For_Main is
begin
        Looper_1;
        Looper_2;
        Looper_3;
end For_Main;


package Loopers is
        procedure Looper_1;
        procedure Looper_2;
        procedure Looper_3;
end Loopers;

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;

        procedure Looper_3 is
                Values : array(1..10) of Integer := (1,2,3,4,5,6,7,8,9,10);
                Indices : array(1..5) of Integer := (2,4,6,8,10);
        begin
                for I in Indices'Range loop
                        Put(Values(Indices(I)),0);
                        if I = Indices'Last then
                                Put_Line(".");
                        else
                                Put(",");
                        end if;
                end loop;
        end Looper_3;

end Loopers;

Agena

Tested with Agena 2.9.5 Win32

for i from 2 to 8 by 2 do
    print( i )
od

Aime

integer i;

i = 0;
while (i < 10) {
    o_winteger(2, i);
    i += 2;
}

o_newline();

ALGOL 60

for i:=5 step 5 until 25 do
  OUTINTEGER(i)

ALGOL 68

The ALGOL 68 "universal" for/while loop:

 [ for index ] [ from first ] [ by increment ] [ to last ] [ while condition ] do statements od
 The minimum form of a "loop clause" is thus: do statements od # an infinite loop #

The formal specification of ALGOL 68 states:

for i from u1 by u2 to u3 while condition do action od

"is thus equivalent to the following void-closed-clause:"

begin int f:= u1, int b = u2, t = u3;
   step2:
     if (b > 0 ∧ f ≤ t) ∨ (b < 0 ∧ f ≥ t) ∨ b = 0
     then int i = f;
         if condition
         then action; f +:= b; go to step2
         fi
     fi
end

Note: Highlighting is as per the formal specification, c.f. Category:ALGOL 68#Example of different program representations.

There are several unusual aspects of the construct:

    • only the 'do ~ od' portion was compulsory, in which case the loop will iterate indefinitely.
    • thus the clause 'to 100 do ~ od', will iterate only 100 times.
    • the while "syntactic element" allowed a programmer to break from a for loop early. eg
int sum sq:=0;
for i while
  sum sq ≠ 70 × 70
do
  sum sq +:= i ↑ 2
od 

Subsequent "extensions" to the standard Algol68 allowed the to syntactic element to be replaced with upto and downto to achieve a small optimisation. The same compilers also incorporated:

  • until(C) - for late loop termination.
  • foreach(S) - for working on arrays in parallel.

ALGOL W

begin
    for i := 3 step 2 until 9 do write( i )
end.

ALGOL-M

BEGIN
    INTEGER I;
    FOR I := 1 STEP 3 UNTIL 19 DO
        WRITE( I );
END

AppleScript

repeat with i from 2 to 10 by 2
	log i
end repeat

ARM Assembly

Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI  */
/*  program loopstep2.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ MAXI,   20
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessResult:  .ascii "Counter = "      @ message result
sMessValeur:   .fill 12, 1, ' '
                   .asciz "\n"
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss 
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main 
main:                @ entry of program 
    push {fp,lr}      @ saves 2 registers 
    mov r4,#0
1:    @ begin loop 
    mov r0,r4
    ldr r1,iAdrsMessValeur     @ display value
    bl conversion10             @ call function with 2 parameter (r0,r1)
    ldr r0,iAdrszMessResult
    bl affichageMess            @ display message
    add r4,#2                   @ increment counter by 2
    cmp r4,#MAXI              @
    ble 1b                @ loop

100:   @ standard end of the program 
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    svc #0                       @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszMessResult:         .int szMessResult
/******************************************************************/
/*     display text with size calculation                         */ 
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}      @ save  registres
    mov r2,#0                  @ counter length 
1:      @ loop length calculation 
    ldrb r1,[r0,r2]           @ read octet start position + index 
    cmp r1,#0                  @ if 0 its over 
    addne r2,r2,#1            @ else add 1 in the length 
    bne 1b                    @ and loop 
                                @ so here r2 contains the length of the message 
    mov r1,r0        			@ address message in r1 
    mov r0,#STDOUT      		@ code to write to the standard output Linux 
    mov r7, #WRITE             @ code call system "write" 
    svc #0                      @ call systeme 
    pop {r0,r1,r2,r7,lr}        @ restaur des  2 registres */ 
    bx lr                       @ return  
/******************************************************************/
/*     Converting a register to a decimal                                 */ 
/******************************************************************/
/* r0 contains value and r1 address area   */
conversion10:
    push {r1-r4,lr}    @ save registers 
    mov r3,r1
    mov r2,#10

1:	   @ start loop
    bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48        @ digit	
    strb r1,[r3,r2]  @ store digit on area
    sub r2,#1         @ previous position
    cmp r0,#0         @ stop if quotient = 0 */
    bne 1b	          @ else loop
    @ and move spaces in first on area
    mov r1,#' '   @ space	
2:	
    strb r1,[r3,r2]  @ store space in area
    subs r2,#1       @ @ previous position
    bge 2b           @ loop if r2 >= zéro 

100:	
    pop {r1-r4,lr}    @ restaur registres 
    bx lr	          @return
/***************************************************/
/*   division par 10   signé                       */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*  
/* and   http://www.hackersdelight.org/            */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */	
/* r1 remainder  */
divisionpar10:	
  /* r0 contains the argument to be divided by 10 */
    push {r2-r4}   /* save registers  */
    mov r4,r0 
    mov r3,#0x6667   @ r3 <- magic_number  lower
    movt r3,#0x6666  @ r3 <- magic_number  upper
    smull r1, r2, r3, r0   @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) 
    mov r2, r2, ASR #2     /* r2 <- r2 >> 2 */
    mov r1, r0, LSR #31    /* r1 <- r0 >> 31 */
    add r0, r2, r1         /* r0 <- r2 + r1 */
    add r2,r0,r0, lsl #2   /* r2 <- r0 * 5 */
    sub r1,r4,r2, lsl #1   /* r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10) */
    pop {r2-r4}
    bx lr                  /* leave function */
/***************************************************/
/* integer division unsigned                       */
/***************************************************/
division:
    /* r0 contains dividend */
    /* r1 contains divisor */
    /* r2 returns quotient */
    /* r3 returns remainder */
    push {r4, lr}
    mov r2, #0                @ init quotient
    mov r3, #0                @ init remainder
    mov r4, #32               @ init counter bits
    b 2f
1:          @ loop 
    movs r0, r0, LSL #1     @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)
    adc r3, r3, r3           @ r3 <- r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C 
    cmp r3, r1               @ compute r3 - r1 and update cpsr 
    subhs r3, r3, r1        @ if r3 >= r1 (C=1) then r3 ? r3 - r1 
    adc r2, r2, r2           @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C 
2:
    subs r4, r4, #1          @ r4 <- r4 - 1 
    bpl 1b                  @ if r4 >= 0 (N=0) then loop
    pop {r4, lr}
    bx lr

Arturo

loop 0..10 .step:2 'i [
	print i
]
Output:
0
2
4
6
8
10

AutoHotkey

SetBatchLines, -1
iterations := 5
step := 10
iterations *= step
Loop,  % iterations
{
   If Mod(A_Index, step)
      Continue
   MsgBox, % A_Index
}
ExitApp

Avail

For each i from 0 to 100 by 7 do [Print: “i” ++ " is a multiple of 7!\n";];

Note the 0 to 100 by 7 segment isn't a fixed part of the loop syntax, but a call to the _to_by_ method, which returns a tuple of integers in a range separated by a particular step size.

AWK

BEGIN {
  for (i= 2; i <= 8; i = i + 2) {
    print i
  }
  print "Ain't never too late!"
}

Axe

Axe does not support a step size other than 1. However, one can modify the increment variable inside the loop to accomplish the same task.

This example increments by 2:

For(I,0,10)
 Disp I▶Dec,i
 I++
End

Bait

fun main() {
	// Print all single digit odd numbers
	for i := 1; i < 10; i += 2 {
		println(i)
	}
}

BASIC

Applesoft BASIC

FOR I = 2 TO 8 STEP 2 : PRINT I; ", "; : NEXT I : PRINT "WHO DO WE APPRECIATE?"

BaCon

This prints all odd digits:

FOR i = 1 TO 10 STEP 2
    PRINT i
NEXT

Basic

Works with: QuickBasic version 4.5
for i = 2 to 8 step 2
   print i; ", ";
next i
print "who do we appreciate?"

BASIC256

for i = 1 to 21 step 2
	print i; " ";
next i
end

BBC BASIC

      FOR n = 2 TO 8 STEP 1.5
        PRINT n
      NEXT
Output:
         2
       3.5
         5
       6.5
         8

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4
10 for i = 1 to 21 step 2
20   print i;
30 next i

Commodore BASIC

10 FOR I = 1 TO 10 STEP 2
20 PRINT I
30 NEXT

FreeBASIC

' FB 1.05.0 Win64

For i As Integer = 1 To 21 Step 2
  Print i; " ";
Next
Print
Sleep

Gambas

Click this link to run this code

Public Sub Main()
Dim siCount As Short

For siCount = 1 To 50 Step 5
  Print "Gambas is great!"
Next

End
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!
Gambas is great!

GW-BASIC

Works with: BASICA
Works with: PC-BASIC version any
10 FOR I = 1 TO 21 STEP 2
20   PRINT I;
30 NEXT I

IS-BASIC

100 FOR I=1 TO 10 STEP 2
110   PRINT I
120 NEXT

Liberty BASIC

for i = 2 to 8 step 2
   print i; ", ";
next i
print "who do we appreciate?"
end

Microsoft Small Basic

For i = 0 To 100 Step 2
  TextWindow.WriteLine(i)
EndFor

Minimal BASIC

Works with: QBasic
Works with: QuickBasic
Works with: Applesoft BASIC
Works with: BASICA
Works with: Chipmunk Basic
Works with: GW-BASIC
Works with: MSX BASIC
Works with: Just BASIC
Works with: Liberty BASIC
Works with: Run BASIC
Works with: Yabasic
10 FOR I = 1 TO 21 STEP 2
20   PRINT I; " ";
30 NEXT I
40 END

MSX Basic

10 FOR I = 1 TO 21 STEP 2
20   PRINT I;
30 NEXT I

NS-HUBASIC

10 FOR I=1 TO 10 STEP 2
20 PRINT I
30 NEXT
Output:
 1  3  5  7  9  11  13  15  17  19  21

PureBasic

For i = -15 To 25 Step 5
  Debug i
Next i
Output:
-15
-10
-5
0
5
10
15
20
25

Decrementing with step

For i = 10 To 0 Step -2
  Debug i
Next ; i is optional
Output:
10
8
6
4
2
0

QB64

For i% = 0 to 10 Step 2 
     Print i%
Next            'To be more explicit use "Next i%"
Output:

A newline is inserted automatically after the Print statement

0
2
4
6
8
10

We can also decrement with stepping

For i% = 10 to 0 Step -2 
     Print i%
Next i
Output:
10
8
6
4
2
9

QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
FOR i = 1 TO 21 STEP 2
  PRINT i;
NEXT i

Quite BASIC

10 FOR I = 1 TO 21 STEP 2
20   PRINT I; " ";
30 NEXT I

Run BASIC

for i = 2 to 8 step 2
   print i; ", ";
next i
print "who do we appreciate?"
Output:
2, 4, 6, 8, who do we appreciate?

smart BASIC

Notice how the ampersand (&) is used to concatenate the variable with the text instead of a semicolon.

FOR n = 2 TO 8 STEP 2
   PRINT n & "..";
NEXT n
PRINT "who do we appreciate?"
END

TI-83 BASIC

Prints numbers from 0 to 100 stepping by 5.

:For(I,0,100,5
:Disp I
:End

TI-89 BASIC

Local i
For i, 0, 100, 5
    Disp i
EndFor

Tiny BASIC

    REM TinyBasic does not have a for-loop construct.
    REM Equivalent using conditional jump:

    LET i = 1
10  IF i > 21 THEN GOTO 20
    PRINT i
	LET i = i + 2
	GOTO 10
20  END

True BASIC

FOR i = 1 TO 21 STEP 2
    PRINT i; " ";
NEXT i
END
Output:
1 3 5 7 9 11 13 15 17 19 21

Since TrueBasic does not distinguish between integer or real values, we can increment using decimal values as well

FOR i = 1 TO 5 STEP .5
    PRINT i
NEXT i
END
Output:
1
1.5
2
2.5
3
3.5
4
4.5
5

Visual Basic

Works with: Visual Basic version VB6 Standard
Sub MyLoop()
    For i = 2 To 8 Step 2
        Debug.Print i;
    Next i
    Debug.Print
End Sub
Output:
 2  4  6  8 

Visual Basic .NET

Works with: Visual Basic .NET version .NET Core 3.0
Imports System.Console
Module Program
    Sub Main()
        For i = 2 To 8 Step 2
            Write($"{i}, ")
        Next
        WriteLine("who do we appreciate?")
    End Sub
End Module
Output:
2, 4, 6, 8, who do we appreciate?
Works with: Visual Basic .NET version 2011
Public Class FormPG
    Private Sub FormPG_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim i As Integer, buffer As String
        buffer = ""
        For i = 2 To 8 Step 2
            buffer = buffer & i & " "
        Next i
        Debug.Print(buffer)
    End Sub
End Class
Output:
2 4 6 8 

XBasic

Works with: Windows XBasic
PROGRAM "forby"

DECLARE FUNCTION Entry()

FUNCTION Entry()
  FOR i% = 0 TO 100 STEP 2
    PRINT FORMAT$("###", i%)
  NEXT i%
END FUNCTION
END PROGRAM

Yabasic

for i = 1 to 21 step 2
    print i, " ";
next i
print
end

ZX Spectrum Basic

10 FOR l = 2 TO 8 STEP 2
20 PRINT l; ", ";
30 NEXT l
40 PRINT "Who do we appreciate?"

Batch File

@echo off
for /l %%A in (1,2,10) do (
     echo %%A
)
Output:
>Sample.BAT
1
3
5
7
9

>

bc

for (i = 2; i <= 10; i += 2) {
    i
}

Befunge

Translation of: C
1 >:.55+,v
@_^#`9:+2<

C

This prints all odd digits:

int i;
for(i = 1; i < 10; i += 2)
  printf("%d\n", i);

C#

using System;
 
class Program {
    static void Main(string[] args) {    
        for (int i = 2; i <= 8; i+= 2) {        
            Console.Write("{0}, ", i);
        }

        Console.WriteLine("who do we appreciate?");
    }
}

C++

This prints all odd digits:

for (int i = 1; i < 10; i += 2)
  std::cout << i << std::endl;

C3

Print all odd digits:

for (int i = 1; i < 10; i += 2) io::printfn("%d", i);

Ceylon

shared void run() {
	
	for(i in (2..8).by(2)) {
		process.write("``i`` ");
	}
	print("who do we appreciate?");
}

Chapel

// Can be set on commandline via --N=x
config const N = 3; 

for i in 1 .. 10 by N {
  writeln(i);
}
Output:
$ ./loopby
1
4
7
10

$ ./loopby --N=4
1
5
9

ChucK

Chuck style

SinOsc s => dac;

for (0 => int i; i < 2000; 5 +=> i )
{
    i => s.freq;
    100::ms => now;
}

General purpose style:

for (0 => int i; i < 2000; 5 +=> i )
{
    <<< i >>>;
}

Clojure

The first example here is following the literal specification, but is not idiomatic Clojure code. The second example achieves the same effect without explicit looping, and would (I think) be viewed as better code by the Clojure community.

(loop [i 0]
  (println i)
  (when (< i 10)
    (recur (+ 2 i))))

(doseq [i (range 0 12 2)] 
  (println i))

CLU

% This prints all odd digits

start_up = proc ()
    po: stream := stream$primary_output()
    
    for i: int in int$from_to_by(1, 10, 2) do
        stream$putl(po, int$unparse(i))
    end
end start_up

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Display-Odd-Nums.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  I PIC 99.

       PROCEDURE DIVISION.
           PERFORM VARYING I FROM 1 BY 2 UNTIL 10 < I
               DISPLAY I
           END-PERFORM

           GOBACK
           .

ColdFusion

<cfloop from="0" to="99" step="3" index="i">
  <Cfoutput>#i#</Cfoutput>
</cfloop>

Common Lisp

(format t "~{~S, ~}who do we appreciate?~%" (loop for i from 2 to 8 by 2 collect i))
Output:
2, 4, 6, 8, who do we appreciate?

Using DO

(do ((n 0 (incf n (+ (random 3) 2))))	; Initialize to 0 and set random step-value 2, 3 or 4
    ((> n 20))				; Break condition
  (print n))				; On every loop print value
Output:
0 
2 
4 
8 
10 
13 
15 
17 
20 

D

import std.stdio, std.range;

void main() {
    // Print odd numbers up to 9.
    for (int i = 1; i < 10; i += 2)
        writeln(i);

    // Alternative way.
    foreach (i; iota(1, 10, 2))
        writeln(i);
}
Output:
1
3
5
7
9
1
3
5
7
9

Dao

# first value: 1
# max value: 9
# step: 2
for( i = 1 : 2 : 9 ) io.writeln( i )

Dart

main() {
  for (int i = 1; i <= 21; i += 2) print(i);
}

Delphi

Delphi's For loop doesn't support a step value. It would have to be simulated using something like a While loop.

program LoopWithStep;
 
{$APPTYPE CONSOLE}
 
var
  i: Integer;
begin
  i:=2;
  while i <= 8 do begin
    WriteLn(i);
    Inc(i, 2);
  end;
end.
Output:
2
4
6
8

Dragon

for(i = 2, i <= 8,i += 2){
   show ", " + i 
}
showln "who do we appreciate?"

DWScript

var i : Integer;

for i := 2 to 8 step 2 do
   PrintLn(i);
Output:
2
4
6
8

Dyalect

//Prints odd numbers from 1 to 10
for i in 1^2..10 {
    print(i)
}

E

There is no step in the standard numeric range object (a..b and a..!b) in E, which is typically used for numeric iteration. An ordinary while loop can of course be used:

var i := 2
while (i <= 8) {
    print(`$i, `)
    i += 2
}
println("who do we appreciate?")

A programmer frequently in need of iteration with an arbitrary step should define an appropriate range object:

def stepRange(low, high, step) {
    def range {
        to iterate(f) {
            var i := low
            while (i <= high) {
                f(null, i)
                i += step
            }
        }
    }
    return range
}

for i in stepRange(2, 9, 2) {
  print(`$i, `)
}
println("who do we appreciate?")

The least efficient, but perhaps convenient, solution is to iterate over successive integers and discard undesired ones:

for i ? (i %% 2 <=> 0) in 2..8 {
    print(`$i, `)
}
println("who do we appreciate?")

EasyLang

# Prints even numbers from 0 to 100
for i = 0 step 2 to 100
   print i
.

EchoLisp

Steps may be integers, float, rationals.

(for ((i (in-range 0 15 2))) (write i))
    0 2 4 6 8 10 12 14

(for ((q (in-range 0 15 14/8))) (write q))
    0 7/4 7/2 21/4 7 35/4 21/2 49/4 14 

(for ((x (in-range 0 15 PI))) (write x))
    0 3.141592653589793 6.283185307179586 9.42477796076938 12.566370614359172

Ela

open monad io
 
for m s n | n > m = do return ()
          | else = do
              putStrLn (show n) 
              for m s (n+s)
 
_  = for 10 2 0 ::: IO
Output:
0
2
4
6
8
10

Elena

ELENA 6.x

public program()
{
    for(int i := 2; i <= 8; i += 2  )
    {
        console.writeLine(i)
    }
}

Elixir

defmodule Loops do
  def for_step(n, step) do
    IO.inspect Enum.take_every(1..n, step)
  end
end

Loops.for_step(20, 3)
Output:
[1, 4, 7, 10, 13, 16, 19]

or

iex(1)> Stream.iterate(1, &(&1+2)) |> Enum.take(10)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

EMal

for int i = 2; i <= 8; i+= 2 do write(i + ", ") end
writeLine("who do we appreciate?")
Output:
2, 4, 6, 8, who do we appreciate?

Erlang

%% Implemented by Arjun Sunel
%% for_loop/4 by Bengt Kleberg.
-module(loop_step).
-export([main/0, for_loop/1, for_loop/4]).
 
 % This Erlang code for "For Loop" is equivalent to: " for (i=start;  i<end ; i=i+2){ printf("* ");} " in C language. 
 
main() ->
	for_loop(1).    
  
 for_loop( N ) ->
	for_loop( N, 4, 2, fun() -> io:fwrite("* ") end ).

for_loop( I, End, Step, Do ) when N < End ->
    Do(),
    for_loop( I+Step, End, Step, Do );
for_loop( _I, _End, _Step, _Do ) -> ok.
Output:
* * ok

ERRE

      FOR N=2 TO 8 STEP 1.5 DO
        PRINT(N)
      END FOR
Output:
         2
       3.5
         5
       6.5
         8

Euphoria

for i = 1 to 10 by 2 do
    ? i
end for

As a note, ? something is shorthand for:

print(1, something)
puts(1, "\n")

print() differs from puts() in that print() will print out the actual sequence it is given. If it is given an integer, or an atom (Any number that is not an integer), it will print those out as-is.

F#

for i in 2..2..8 do
   printf "%d, " i
printfn "done"
Output:
2, 4, 6, 8, done

Factor

Prints odd digits.

1 10 2 <range> [ . ] each

FALSE

2[$9\>][$.", "2+]#"who do we appreciate!"

Fantom

class Main
{
  public static Void main ()
  {
    Int step := 5
    for (Int i := 0; i < 100; i += step)
    {
      echo (i)
    }
  }
}

FBSL

#APPTYPE CONSOLE

DIM n AS INTEGER
FOR n = 2 TO 8 STEP 2
    PRINT n;
    IF n < 8 THEN PRINT " ";
NEXT
PRINT ", who will we obliterate?"
PAUSE

Fermat

for i = 1 to 100 by 13 do !i;!' '; od
Output:
1 14 27 40 53 66 79 92

FOCAL

If a FOR statement has three parameters, they are (in order) the start, the step, and the end; if only two parameters are supplied, they are taken to be the start and the end. The step is then set to 1.

FOR I = 1,3,10; TYPE I, !

Forth

: test
  9 2 do
    i .
  2 +loop
  ." who do we appreciate?" cr ;

Fortran

Works with: Fortran version 90 and later
do i = 1,10,2
   print *, i
end do
Works with: Fortran version 77 and later
      PROGRAM STEPFOR
        INTEGER I

C       This will print all even numbers from -10 to +10, inclusive.
        DO 10 I = -10, 10, 2
          WRITE (*,*) I
   10   CONTINUE

        STOP
      END

Frink

for a = 1 to 100 step 5
   println[a]

All values may have units of measure, in which case a specified step is required:

for a = 1 km to 3 km step 1 meter
   println[a]

FutureBasic

Str15 s(11)
long i

s(0) = "Somewhere"
s(2) = " over"
s(4) = " the"
s(6) = " rainbow" + chr$(13)
s(8) = "Bluebirds"
s(10) = " fly."

for i = 0 to 10 step 2
print s(i);
next

HandleEvents
Output:
Somewhere over the rainbow
Bluebirds fly.

GML

for(i = 0; i < 10; i += 2)
    show_message(string(i))

GAP

  1. Use a range [a, b .. c], where the step is b-a (b is the value following a), and c-a must be a multiple of the step.
for i in [1, 3 .. 11] do
    Print(i, "\n");
od;

1
3
5
7
9
11

Go

This prints all odd digits:

for i := 1; i < 10; i += 2 {
  fmt.Printf("%d\n", i)
}

Groovy

"for" loop:

for(i in (2..9).step(2)) {
    print "${i} "
}
println "Who do we appreciate?"

"each() method: Though technically not a loop, most Groovy programmers would use the slightly more terse "each()" method on the collection itself, instead of a "for" loop.

(2..9).step(2).each {
    print "${it} "
}
println "Who do we appreciate?"
Output:
2 4 6 8 Who do we appreciate?

Go Team!

Haskell

import Control.Monad (forM_)
main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", "))
          putStrLn "who do we appreciate?"

Haxe

While Haxe's for-loop does not allow you to directly specify the step size, it is easy to create an iterator that allows you to do that.

class Step {
  var end:Int;
  var step:Int;
  var index:Int;

  public inline function new(start:Int, end:Int, step:Int) {
    this.index = start;
    this.end = end;
    this.step = step;
  }

  public inline function hasNext() return step > 0 ? end >= index : index >= end;
  public inline function next() return (index += step) - step;
}

class Main {
  static function main() {
    for (i in new Step(2, 8, 2)) {
      Sys.print('$i ');
    }
    Sys.println('WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!');
  }
}
Output:
2 4 6 8 WHOM do we appreciate? GRAMMAR! GRAMMAR! GRAMMAR!

hexiscript

for let i 0; i <= 50; let i (i + 5)
  println i
endfor

HicEst

DO i = 1, 6, 1.25 ! from 1 to 6 step 1.25
   WRITE() i
ENDDO

HolyC

This prints all odd digits:

U8 i;
for (i = 1; i < 10; i += 2)
  Print("%d\n", i);

Hy

(for [i (range 1 10 2)] (print i))

Icon and Unicon

Icon and Unicon accomplish loop stepping through the use of a generator, the ternary operator to-by, and the every clause which forces a generator to consume all of its results. Because to-by is an operator it has precedence (just higher than assignments) and associativity (left) and can be combined with other operators.

   every 1 to 10 by 2                       # the simplest case that satisfies the task, step by 2

   every 1 to 10                            # no by, step is 1 by default
   every EXPR1 to EXPR2 by EXPR3 do EXPR4   # general case - EXPRn can be complete expressions including other generators such as to-by, every's do is optional
   steps := [2,3,5,7]                       # a list
   every i := 1 to 100 by !steps            # . more complex, several passes with each step in the list steps, also we might want to know what value we are at
   every L[1 to 100 by 2]                   # as a list index
   every i := 1 to 100 by (k := !steps)     # . need () otherwise := generates an error
   every 1 to 5 to 10                       # simple case of combined to-by - 1,..,10, 2,..10, ..., 5,..,10
   every 1 to 15 by 2 to 5                  # combined to-by
   every (1 to 15 by 2) to 5                # . made explicit

   every writes( (TO_BY_EXPR) | "\n", " " ) # if you want to see how any of these work

The ability to combine to-by arbitrarily is quite powerful. Yet it can lead to unexpected results. In cases of combined to-by operators the left associativity seems natural where the by is omitted. In cases where the by is used it might seem more natural to be right associative. If in doubt parenthesize.

Insitux

(for i (range 0 10 2)
  (print i)
  (continue))

;or
(loop 5 i
  (print (* i 2)))

Io

for(i,2,8,2,
    write(i,", ")
)
write("who do we appreciate?")

J

    ' who do we appreciate?' ,~ ":  2 * >: i.4
2 4 6 8 who do we appreciate?

Note that an expression of the form (start, step) (p. i.) count will generate the specified numbers (p. is J's polynomial primitive, i. is J's index generator). So, to generate the above sequence of integers we could have used:

   0 2 (p. i.) 5
0 2 4 6 8

Or, using an "actual" for loop:

   3 :0''
  r=.$0
  for_n. 2 * >: i.4 do.
    r=.r,n
  end.
  ' who do we appreciate?' ,~ ":n
)
2 4 6 8 who do we appreciate?

That said, note also that J's steps verb lets us specify how many steps to take:

   i:8
_8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8
   i:8j8
_8 _6 _4 _2 0 2 4 6 8

Or, if we prefer, we could borrow the definition of thru from the Downward for task and then filter for the desired values:

   thru=: <./ + i.@(+*)@-~

Example use:

   (#~ 0 = 2&|) 1 thru 20
2 4 6 8 10 12 14 16 18 20
   (#~ 0 = 3&|) 1 thru 20
3 6 9 12 15 18
   (#~ 1 = 3&|) 1 thru 20
1 4 7 10 13 16 19

And, of course, like filtering in any language, this approach supports non-constant step sizes, either by applying a function to each argument individually:

   (#~ 1&p:) 1 thru 20
2 3 5 7 11 13 17 19

Or, by inserting a combining function between each value:

   (-&{.,])/ 1 thru 20
_10 11 _9 12 _8 13 _7 14 _6 15 _5 16 _4 17 _3 18 _2 19 _1 20

Other structural approaches can also be viable...

Java

for(int i = 2; i <= 8;i += 2){
   System.out.print(i + ", ");
}
System.out.println("who do we appreciate?");

JavaScript

var output = '',
    i;
for (i = 2; i <= 8; i += 2) {
   output += i + ', ';
}
output += 'who do we appreciate?';
document.write(output);

In a functional idiom of JavaScript, however, we will only be able to compose this computation within the superordinate expressions of our program if it has the the form of an expression returning a value, rather than that of a statement which fires off side-effects but returns no value.

Following the example of languages like Haskell and J on this page, we can begin by generating the stepped series as an expression. In functional JavaScript we will typically replace a state-changing loop with a non-mutating map or fold, writing, for example, something like:

// range(iMax)
// range(iMin, iMax)
// range(iMin, iMax, dI)
function range() {
  var lngArgs = arguments.length,
    lngMore = lngArgs - 1;

  iMin = lngMore ? arguments[0] : 1;
  iMax = arguments[lngMore ? 1 : 0];
  dI = lngMore > 1 ? arguments[2] : 1;

  return lngArgs ? Array.apply(null, Array(
    Math.floor((iMax - iMin) / dI) + 1
  )).map(function (_, i) {
    return iMin + (dI * i);
  }) : [];
}

console.log(
  range(2, 8, 2).join(', ') + ', who do we appreciate ?'
);

Output:

2, 4, 6, 8, who do we appreciate ?

jq

To generate the stream: 2,4,6,8:

# If your version of jq does not have range/3, use this:
def range(m;n;step): range(0; ((n-m)/step) ) | m + (. * step);

range(2;9;2)

Example:

reduce range(2;9;2) as $i
   (""; . + "\($i), ") +
   "whom do we appreciate?"

Julia

for i in 2:2:8
    print(i, ", ")
end
println("whom do we appreciate?")

Kotlin

// version 1.0.6

fun main(args: Array<String>) {
    for (i in 1 .. 21 step 2) print("$i ")
}
Output:
1 3 5 7 9 11 13 15 17 19 21

LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

Lambdatalk

{def loops_for_with_a_specified_step
 {lambda {:a :b :step}
  {if {>= :a :b}
   then (end of loop)
   else :a {loops_for_with_a_specified_step {+ :a :step} :b :step}}}}  
-> loops_for_with_a_specified_step  

{loops_for_with_a_specified_step 0 10 2}
-> 0 2 4 6 8 (end of loop)

a more simple way:

{S.map {lambda {:i} :i} {S.serie 0 9 2}}
-> 0 2 4 6 8

Lang5

: <range>  over iota swap * rot + tuck swap <= select ; : tuck  swap over ;
: >>say.(*)  . ;
1 10 2 <range> >>say.

langur

for .i = 1; .i < 10; .i += 2 {
    writeln .i
}
Output:
1
3
5
7
9

Lasso

loop(-to=100, -from=1, -by=2) => {^
    loop_count
    '\r' // for formatting
^}

LDPL

# Display the even numbers up to twenty.

data:
i is number

procedure:
for i from 0 to 21 step 2 do
    display i lf
repeat
Output:
0
2
4
6
8
10
12
14
16
18
20

LIL

The inc command accepts a value to add to the variable, 1 if not specified.

for {set i 1} {$i < 15} {inc i 3} {print $i}
Output:
# for {set i 1} {$i < 15} {inc i 3} {print $i}
1
4
7
10
13
#

Lingo

Lingo loops don't support a "step" parameter, so it has to be implemented manually:

step = 3
repeat with i = 0 to 10
  put i
  i = i + (step-1)
end repeat
Output:
-- 0
-- 3
-- 6
-- 9

Lisaac

1.to 9 by 2 do { i : INTEGER;
  i.print;
  '\n'.print;
};

LiveCode

repeat with n = 0 to 10 step 2
    put n after loopn
    if n is not 10 then put comma after loopn
end repeat
put loopn

Output

0,2,4,6,8,10

for [i 2 8 2] [type :i type "|, |] print [who do we appreciate?]

Lua

for i=2,9,2 do
  print(i)
end
Output:
2
4
6
8

M2000 Interpreter

A for loop

Str$(i) always return decimal separator as "." format$() use same as Locale number specify. So here we use "," from Locale 1036. Str$() place a space before number if it is positive. We can use str$(i, "") to trim lead space. Here we use a space in format$ before number (and for negative numbers)

For this task we use single float numbers, and we make the loop one time from lower to higher value, and one time form higher to lower value.

Module LoopFor {
      Locale 1036
      Document doc$
      \\ define i as a single
      def single i
      for i=1 to 21 step 5/3
            Print i
            doc$=format$(" {0}", i)
      next i
      doc$={
      }
      \\ make i as a single
      for i=21 to 1 step 5/3
            Print i
            doc$=format$(" {0}", i)
      next i
      clipboard doc$
      report doc$
}
LoopFor
Output:
 1 2,66667 4,33333 6 7,66667 9,33333 11 12,66667 14,33333 16 17,66667 19,33333 21
 21 19,33333 17,66667 16 14,33334 12,66667 11 9,33333 7,66667 6 4,33333 2,66667 1

Iterator step 2

a=("A", "B", "C", "D", "E", "F", "Z")
k=Each(a)
While k {
      Print Array$(k),
      k=Each(a, k^+2)   ' set start again
}
Print
\\ a list of keys (unique keys allowed)
Inventory b="A", "B", "C", "D", "E", "F", "Z"
k=Each(b)
While k {
      Print Eval$(k), ' return keys as values, because no value exist yet for each key.
      k=Each(b, k^+2)
}
Print
Output:
A   C   E   Z
A   C   E   Z

M4

define(`for',
   `ifelse($#,0,``$0'',
   `ifelse(eval($2<=$3),1,
   `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl

for(`x',`1',`5',`3',`x
')
Output:
1
4

Maple

for i from 2 to 8 by 2 do
  i;
end do;
Output:
                               2
                               4
                               6
                               8

Mathematica/Wolfram Language

Do[
 Print[i],
 {i, 1, 20, 4}]
Output:
1
5
9
13
17

MATLAB / Octave

    for k = 0:10:100,
        printf('%d\n',k)
    end;

A vectorized version of the code is

  printf('%d\n',0:10:100);

Maxima

for i: 1 step 2 thru 10 do print(i);
/* 1
   3
   5
   7 */

MAXScript

for i = 0 to 10 by 2 do format "%\n" i

Output:

 
0
2
4
6
8
10
OK

min

Printing the even numbers in [0,10):

Works with: min version 0.19.6
0 (dup 10 >=) 'pop (puts 2 +) () linrec

MiniScript

for i in range(1,20,4)
    print i
end for
Output:
1
5
9
13
17

МК-61/52

1	П0	ИП0	3	+	П0	1	0	-	x#0
02	С/П

In this example, the step is 3, the lowest value is 1 and the upper limit is 10.

Modula-2

MODULE ForBy;
  IMPORT InOut;

  VAR
    i: INTEGER;

BEGIN
  FOR i := 0 TO 100 BY 2 DO
    InOut.WriteInt(i, 3);
    InOut.WriteLn
  END
END ForBy.

Modula-3

FOR i := 1 TO 100 BY 2 DO
  IO.Put(Fmt.Int(i) & " ");
END;

MUMPS

FOR I=65:3:122 DO
 .WRITE $CHAR(I)," "
Output:
A D G J M P S V Y \ _ b e h k n q t w z

Nemerle

for (i = 2; i <= 8; i +=2)
foreach (i in [2, 4 .. 8])

NetRexx

/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

say
  say 'Loops/For with a specified step'

  loop i_ = -1.4 to 10.6 by 1.7
    say i_.format(3, 1) || '\0'
    end i_
  say
Output:
D:\>java lst

Loops/For with a specified step
 -1.4  0.3  2.0  3.7  5.4  7.1  8.8 10.5

Never

The increment step of the Never for expression can be simple or complex and need not be contiguous.

for (i = 0; i < 10; i += 3)

NewLISP

(for (i 0 10 2)
  (println i))

Nim

for n in 5 .. 9:                 # 5 to 9 (9-inclusive)
  echo n

echo "" # spacer 

for n in 5 ..< 9:                # 5 to 9 (9-exclusive)
  echo n

echo "" # spacer 

for n in countup(0, 16, 4):      # 0 to 16 step 4
  echo n 

echo "" # spacer

for n in countdown(16, 0, 4):    # 16 to 0 step -4
  echo n
Output:
5
6
7
8
9

5
6
7
8

0
4
8
12
16

16
12
8
4
0

N/t/roff

Works with gnu nroff. Example from groff manual, with minimal modifications.

.nr a 0 3
.while (\na < 19) \{\
\n+a
.\}
Output:
3 6 9 12 15 18 21

Nu

Here each {} is used to convert from a range to a list, so that it can be consumed by every

for i in (0..10 | each {} | every 2) {print $i}
Output:
0
2
4
6
8
10

Oberon-2

Works with oo2c Version 2

MODULE LoopForStep;
IMPORT 
  Out;
VAR
  i: INTEGER;
 
BEGIN
  FOR i := 0 TO 10 BY 3 DO
    Out.LongInt(i,0);Out.Ln
  END;
  FOR i := 10 TO 0 BY -3 DO
    Out.LongInt(i,0);Out.Ln
  END
END LoopForStep.

Output:

0
3
6
9
10
7
4
1

Objeck

for(i := 0; i < 10; i += 2;) {
  i->PrintLine();
};

OCaml

# let for_step a b step fn =
    let rec aux i =
      if i <= b then begin
        fn i;
        aux (i+step)
      end
    in
    aux a
  ;;
val for_step : int -> int -> int -> (int -> 'a) -> unit = <fun>

# for_step 0 8 2  (fun i -> Printf.printf " %d\n" i) ;;
 0
 2
 4
 6
 8
- : unit = ()

Octave

for i = 1:2:10
  disp(i)
endfor

Oforth

 1 100 2 step: i [ i println ]

Openscad

/* Loop from 3 to 9 in steps of 2 */

for ( l = [3:2:9] )  {
  echo (l);
}
echo ("on a double white line.");

Oz

for I in 2..8;2 do
   {System.show I}
end
{System.show done}

Panda

Panda doesn't natively have a number generator with steps, so let's add it.

fun for(from,to,step) type integer,integer,integer->integer
  t=to.minus(from).divide(step)
  0..t.times(step).plus(from)
  /test it for(1 6 2) -> 1 3 5

for(1 3 5)

PARI/GP

forstep(n=1,10,2,print(n))

The forstep construct is actually more powerful. For example, to print numbers with last digit relatively prime to 10:

forstep(n=1,100,[2,4,2,2],print(n))

Pascal

See Delphi

Perl

for($i=2; $i <= 8; $i += 2) {
  print "$i, ";
}
print "who do we appreciate?\n";

Phix

{libheader|Phix/basics}}

for i=2 to 8 by 2 do
    printf(1,"%d, ",i)
end for
printf(1,"who do we appreciate?\n")

Phixmonti

/# Rosetta Code problem: https://rosettacode.org/wiki/Loops/For_with_a_specified_step
by Galileo, 11/2022 #/

include ..\Utilitys.pmt

( 2 8 2 ) for print ", " print endfor
"who do we appreciate?" print
Output:
2, 4, 6, 8, who do we appreciate?
=== Press any key to exit ===

PHP

<?php
foreach (range(2, 8, 2) as $i)
    echo "$i, ";
echo "who do we appreciate?\n";
?>
Output:
2, 4, 6, 8, who do we appreciate?

PicoLisp

(for (N 1 (> 10 N) (+ N 2))
   (printsp N) )

Pike

int main() {
   for(int i = 2; i <= 16; i=i+2) {
      write(i + "\n");
   }
}

PILOT

One of the advantages of needing to create loops manually by using conditional jumps is that a step of any integer is just as easy as a step of one.

R  : Prints the odd numbers less than 10.
C  :i = 1
*Loop
T  :#i
C  :i = i + 2
J ( i < 10 )  :*Loop
END:

PL/I

declare (n, i) fixed binary;

get list (n);
do i = 1 to n by 4;
   put skip list (i);
end;

Plain English

Plain English has only one type of loop: an infinite loop that can be given a conditional break or exit. So there is nothing particularly special about this.

To run:
Start up.
Put 0 into a number.
Loop.
If the number is greater than 50, break.
Convert the number to a string.
Write the string to the console.
Add 5 to the number.
Repeat.
Wait for the escape key.
Shut down.

PowerShell

for ($i = 0; $i -lt 10; $i += 2) {
    $i
}

Prolog

If you need a stepping iterator, write one:

for(Lo,Hi,Step,Lo)  :- Step>0, Lo=<Hi.
for(Lo,Hi,Step,Val) :- Step>0, plus(Lo,Step,V), V=<Hi, !, for(V,Hi,Step,Val).

example :- 
  for(0,10,2,Val), write(Val), write(' '), fail.
example.
?- example.
0 2 4 6 8 10 
true.

Adding the following two rules lets you go backwards too:

for(Hi,Lo,Step,Hi)  :- Step<0, Lo=<Hi.
for(Hi,Lo,Step,Val) :- Step<0, plus(Hi,Step,V), Lo=<V, !, for(V,Lo,Step,Val).

Python

Works with: Python version 2.x
for i in xrange(2, 9, 2):
    print "%d," % i,
print "who do we appreciate?"
Works with: Python version 3.x
for i in range(2, 9, 2):
    print("%d, " % i, end="")
print("who do we appreciate?")
Output:
2, 4, 6, 8, who do we appreciate?

Quackery

The step size is specified within the loop, giving many possibilities.

20 times [ i^ echo sp 
           2 step ]
cr
1024 times [ i^ 1+ echo sp
             i^ 1+ step ]
cr
1 56 times [ i^ echo sp 
             i^ swap step ] 
cr
Output:
0 2 4 6 8 10 12 14 16 18 
1 2 4 8 16 32 64 128 256 512 1024 
0 1 1 2 3 5 8 13 21 34 55 

R

for(a in seq(2,8,2)) {
  cat(a, ", ")
}
cat("who do we appreciate?\n")

Here the loop may be done implicitly by first concatenating the string and then printing:

cat(paste(c(seq(2, 8, by=2), "who do we appreciate?\n"), collapse=", "))

Racket

#lang racket

(for ([i (in-range 2 9 2)])
  (printf "~a, " i))
(printf "who do we appreciate?~n")

Raku

(formerly Perl 6)

Works with: Rakudo version 2010.07

Depending on how you define your terms, this task is either trivial or impossible in Raku. for in Raku doesn't have a step value, it's an iteration operator. It iterates through any iterable object passed to it and sets the topic variable to each iterated value in turn. If you close one eye and squint, I guess you could say it has a step value of 1 (or more accurately, Next) and that isn't really changeable. Whatever iterable you pass to it though can have pretty much any value in pretty much any order you desire, so effectively the "step" value is completely unconstrained.

Examples of iterables (not exhaustive):

  • Things that do a positional role:
  • Array
  • List
  • Range
  • Sequence
  • Things that do an associative role:
  • Bag
  • BagHash
  • Hash
  • Map
  • Mix
  • MixHash
  • QuantHash
  • Set
  • SetHash


Probably the most straightforward way to do this is with a sequence. With at least two values on the left-hand side, the sequence operator (...) can infer an arithmetic series. (With at least three values, it can infer a geometric sequence, too.)

for 2, 4 ... 8 {
    print "$_, ";
}
 
say 'whom do we appreciate?';

But there is nothing constraining the sequence to a constant step. Here's one with a random step.

.say for rand, *+rand-.5 ... *.abs>2
Sample output:
0.1594860240843563
-0.11336537297314198
-0.04195945218519992
-0.024844489074366427
-0.20616093727620433
-0.17589258387167517
-0.40547336592612593
0.04561929494516015
0.4886003890463373
0.7843094215547495
0.6413619589945883
1.0694380727281951
1.472290164849169
1.8310404939418325
2.326272380988639

For that matter, the iterated object doesn't need to contain numbers.

.say for <17/32 π banana 👀 :d(7) 🦋>;

Raven

List of numbers:

[ 2 4 6 8 ] each "%d, " print
"who do we appreciate?\n" print

Range:

2 10 2 range each "%d, " print
"who do we appreciate?\n" print
Output:
2, 4, 6, 8, who do we appreciate?

REBOL

for i 2 8 2 [
	prin rejoin [i ", "]]
print "who do we appreciate?"
Output:
2, 4, 6, 8, who do we appreciate?

REXX

version 1

  do x=1  to 10  by 1.5
  say x
  end
Output:
1
2.5
4.0
5.5
7.0
8.5
10.0

version 2

  do thing=1  by  3/2  to 10 
  say  thing
  end

output is the same as above.

version 3

Do v=1  by  3/2  While v**2<30 
  Say  v
  End
Say '('v'**2) is greater than 30 (30.25)'
Output:
1
2.5
4.0
(5.5**2) is greater than 30 (30.25)

Ring

we use step keyword to define step length in this example we print Even numbers between 0 and 10

for i = 0 to 10 step 2 see i + nl next
Output:
2
4
6
8
10

we can use step with double values as well:

for i = 0 to 10 step 0.5 see i + nl next
Output:
0
0.50
1
1.50
2
2.50
3
3.50
4
4.50
5
5.50
6
6.50
7
7.50
8
8.50
9
9.50
10

RPL

Specific increment is given as an argument to the STEP instruction at the end of each loop. Usually, it is a constant value, but it could be a variable if it makes sense.

≪ 1 10 FOR j
      j
   2 STEP

Ruby

2.step(8,2) {|n| print "#{n}, "}
puts "who do we appreciate?"

or:

(2..8).step(2) {|n| print "#{n}, "}
puts "who do we appreciate?"

or:

for n in (2..8).step(2)
  print "#{n}, "
end
puts "who do we appreciate?"

or:

for n in 2.step(by: 2, to: 8)
  print "#{n}, "
end
puts "who do we appreciate?"
Output:
2, 4, 6, 8, who do we appreciate?

Rust

For Rust 1.28 and later:

fn main() {
  for i in (2..=8).step_by(2) {
    print!("{}", i);
  }
  println!("who do we appreciate?!");
}

An alternative which also works in earlier versions of Rust:

fn main() {
    let mut i = 2;
    while i <= 8 {
        print!("{}, ", i);
        i += 2;
    }
    println!("who do we appreciate?!");
}

Salmon

for (x; 2; x <= 8; 2)
    print(x, ", ");;
print("who do we appreciate?\n");

SAS

data _null_;
do i=1 to 10 by 2;
put i;
end;
run;

Sather

See Loops/For#Sather: the implementation for for! allows to specify a step, even though the built-in stepto! can be used; an example of usage could be simply:

    i :INT;
    loop
      i := for!(1, 50, 2);
      -- OR
      -- i := 1.stepto!(50, 2);
      #OUT + i + "\n";
    end;

(Print all odd numbers from 1 to 50)

Scala

for (i <- 2 to 8 by 2) println(i)

Alternatively:

(2 to 8 by 2) foreach println

Scheme

The built-in for-like form in Scheme is the do form:

(do ((i 2 (+ i 2)))  ; list of variables, initials and steps -- you can iterate over several at once
  ((>= i 9))         ; exit condition
  (display i)        ; body
  (newline))

Some people prefer to use the recursive-style and more flexible _named let_ form:

(let loop ((i 2))            ; function name, parameters and starting values
  (cond ((< i 9)
         (display i)
         (newline)
         (loop (+ i 2))))))  ; tail-recursive call, won't create a new stack frame

You can add to the language by wrapping the loop in a function:

(define (for-loop start end step func)
  (let loop ((i start))
    (cond ((< i end)
	   (func i)
	   (loop (+ i step))))))

(for-loop 2 9 2
  (lambda (i)
    (display i)
    (newline)))

... or in a macro, which allows for making the (lambda) implicit:

(define-syntax for-loop
  (syntax-rules () 
    ((for-loop index start end step body ...)
     (let ((evaluated-end end) (evaluated-step step))
       (let loop ((i start))
         (if (< i evaluated-end)
           ((lambda (index) body ... (loop (+ i evaluated-step))) i)))))))

(for-loop i 2 9 2
  (display i)
  (newline))
Output:
2
4
6
8

Scilab

Works with: Scilab version 5.5.1
for i=1:2:10
    printf("%d\n",i)
end
Output:
1
3
5
7
8

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 0 to 10 step 2 do        #  10 is inclusive
      writeln(number);
    end for;

    writeln; # spacer
    
    for number range 10 downto 0 step 2 do
      writeln(number);
    end for;
    
  end func;
Output:
0
2
4
6
8
10

10
8
6
4
2
0

Sidef

for(;;) loop:

for (var i = 2; i <= 8; i += 2) {
    say i
}

for-in loop:

for i in (2 .. (8, 2)) {
    say i
}

.each method:

2.to(8).by(2).each { |i|
    say i
}

Simula

begin
    integer i;
    for i:=5 step 5 until 25 do outint(i, 5)
end

Slate

2 to: 8 by: 2 do: [| :i | Console ; i printString ; ', '].
inform: 'enough with the cheering already!'.

Smalltalk

2 to: 8 by: 2 do: [ :i |
  Transcript show: i; show ', '
].
Transcript showCr: 'enough with the cheering already!'

Spin

Works with: BST/BSTC
Works with: FastSpin/FlexSpin
Works with: HomeSpun
Works with: OpenSpin
con
  _clkmode = xtal1 + pll16x
  _clkfreq = 80_000_000

obj
  ser : "FullDuplexSerial.spin"

pub main | n
  ser.start(31, 30, 0, 115200)

  repeat n from 0 to 19 step 3
    ser.dec(n)
    ser.tx(32)

  waitcnt(_clkfreq + cnt)
  ser.stop
  cogstop(0)
Output:
0 3 6 9 12 15 18

SPL

> n, 1..10,2
  #.output(n)
<

SSEM

Implementing loops with a step other than one is precisely as easy (or as fiddly) as implementing loops with a step equal to one. This example program uses a loop to perform integer division. It should be run with the dividend in storage location 21 and the divisor in storage location 22. To show that it works, we shall ask the machine to count from 387 in steps of -5 and to halt with the accumulator showing the number of times it has done so before producing a negative result.

10101000000000100000000000000000   0. -21 to c
00101000000001100000000000000000   1. c to 20
00101000000000100000000000000000   2. -20 to c
01101000000000010000000000000000   3. Sub. 22
10101000000001100000000000000000   4. c to 21
00000000000000110000000000000000   5. Test
01001000000001000000000000000000   6. Add 18 to CI
00011000000000000000000000000000   7. 24 to CI
11101000000000100000000000000000   8. -23 to CI
01001000000000010000000000000000   9. Sub. 18
00101000000001100000000000000000  10. c to 20
00101000000000100000000000000000  11. -20 to c
11101000000001100000000000000000  12. c to 23
11001000000000000000000000000000  13. 19 to CI
11101000000000100000000000000000  14. -23 to c
00101000000001100000000000000000  15. c to 20
00101000000000100000000000000000  16. -20 to c
00000000000001110000000000000000  17. Stop
10000000000000000000000000000000  18. 1
11111111111111111111111111111111  19. -1
00000000000000000000000000000000  20. 0
11000001100000000000000000000000  21. 387
10100000000000000000000000000000  22. 5
00000000000000000000000000000000  23. 0
10110000000000000000000000000000  24. 13

After executing 1,012 instructions, the computer halts with the correct quotient—77—in the accumulator.

Stata

forvalues i=1(2)10 {
	display "`i'"
}

1
3
5
7
9

Swift

This prints all odd digits:

for i in stride(from: 1, to: 10, by: 2) {
  print(i)
}

Alternately (removed in Swift 3):

for var i = 1; i < 10; i += 2 {
  print(i)
}

Tailspin

Tailspin uses streams not loops

1..9:3 -> !OUT::write
Output:
147

Tcl

for {set i 2} {$i <= 8} {incr i 2} {
    puts -nonewline "$i, "
}
puts "enough with the cheering already!"

TorqueScript

for(%i = 0; %i < 201; %i += 2)
{
	echo(%i);
}

TUSCRIPT

$$ MODE TUSCRIPT
LOOP i=2,9,2
PRINT i
ENDLOOP
Output:
2
4
6
8

UNIX Shell

All these loops iterate 2, 4, 6, 8.

Bourne Shell

Works with: Bourne Shell
x=2
while test $x -le 8; do
        echo $x
        x=`expr $x + 2` || exit $?
done
Works with: Bourne Shell
Library: jot
for x in `jot - 2 8 2`; do echo $x; done

ksh

x=0
while (((x += 2) <= 8))
do
	print -r "$x"
done
Works with: ksh93
for x in {2..8..2}
do
	print -r "$x"
done

Bourne Again Shell

Works with: Bourne Again SHell version 3
for (( x=2; $x<=8; x=$x+2 )); do
  printf "%d, " $x
done
Works with: Bourne Again SHell version 4

Bash v4.0+ has inbuilt support for setting up a step value

for x in {2..8..2} 
do
  echo $x
done

C Shell

Library: jot
foreach x (`jot - 2 8 2`)
	echo $x
end

Ursa

Translation of: Python
decl int i
for (set i 2) (< i 9) (set i (int (+ i 2)))
	out i ", " console
end for
out "who do we appreciate?" endl console

Vala

for (int i = 1; i < 10; i += 2)
  stdout.printf("%d\n", i);

VAX Assembly

                               0000  0000     1 .entry	main,0
                            50   D4  0002     2 	clrf	r0				;init to 0.0
                                     0004     3 loop:
                                 01  0004     4 	nop					;do nothing
             FFF9 50   0A   3E   4F  0005     5 	acbf	#112.0, #1.25, r0, loop		;limit, step
                                     000B     6 
                                 04  000B     7 	ret
                                     000C     8 .end	main

VBA

Sub MyLoop()
    For i = 2 To 8 Step 2
        Debug.Print i;
    Next i
    Debug.Print
End Sub
Output:
 2  4  6  8 

VBScript

buffer = ""
For i = 2 To 8 Step 2
    buffer = buffer & i & " "
Next
WScript.Echo buffer
Output:
2 4 6 8

Vedit macro language

This prints all odd digits in range 1 to 9:

for (#1 = 1; #1 < 10; #1 += 2) {
    Num_Type(#1)
}


Verilog

Imprime todos los números impares

module main;
  integer  i;
  
  initial begin

    for(i = 1; i <= 21; i = i + 2)  $write(i);
  $finish ;
  end
endmodule


Vim Script

for i in range(2, 10, 2)
    echo i
endfor
Output:
2                                                                                                                 
4                                                                                                                 
6                                                                                                                 
8                                                                                                                 
10

V (Vlang)

This prints all odd digits:

for i := 1; i<10; i+=2 {
    println(i)
}

Vorpal

for(i = 2, i <= 8, i = i + 2){
   i.print()
}

Wart

for i 2 (i <= 8) (i <- i+2)
  prn i

Wren

There is currently no direct way to incorporate a step into a for loop but we can simulate it by declaring a second variable at the start of the loop which maps the loop variable to the value we want or we can simply use a while loop instead.

// Print odd numbers under 20.
for (i in 1..10) {
    var j = 2*i - 1
    System.write("%(j) ")
}

System.print("\n")

// Do the same using a 'while' loop.
var k = 1
while (k < 20) {
    System.write("%(k) ")
    k = k + 2
}
System.print()
Output:
1 3 5 7 9 11 13 15 17 19 

1 3 5 7 9 11 13 15 17 19 


Library: Wren-iterate

A further and more general approach is to use a wrapper class (such as the one in the above module) which can iterate over any sequence in a stepped fashion using Wren's iterator protocol.

import "./iterate" for Stepped

// Print odd numbers under 20.
for (i in Stepped.new(1..20, 2)) System.write("%(i) ")
System.print()

// Print first plus every third element thereafter.
for (i in Stepped.new(1..20, 3)) System.write("%(i) ")
System.print()
Output:
1 3 5 7 9 11 13 15 17 19 
1 4 7 10 13 16 19 

XPL0

The 'for' loop always steps by 1 (or -1 for 'downto'). However there is no restriction on how the control variable can be used or manipulated, thus a step by 2 can be implemented like this:

include c:\cxpl\codes;
int I;
[for I:= 2 to 8 do
        [IntOut(0, I);  Text(0, ", ");
        I:= I+1;
        ];
Text(0, "who do we appreciate?");
]
Output:
2, 4, 6, 8, who do we appreciate?

zkl

foreach n in ([1..10,4]) {println(n)}
[1..10,3].pump(Console.println)
Output:
1
5
9

1
4
7
10

A few others:

fcn loop(i=0){println(i); if(i<10)return(self.fcn(i+2))}
(0).pump(10,Console.println,fcn(n){if(n%2)return(Void.Skip); n})

Zig

const std = @import("std");

pub fn main() !void {
    const stdout_wr = std.io.getStdOut().writer();
    var i: u8 = 1;
    while (i < 10) : (i += 2)
        try stdout_wr.print("{d}\n", .{i});
}

With for-loop

const std = @import("std");
const stdout = @import("std").io.getStdOut().writer();

pub fn main() !void {
    for (1..10) |n| {
        if (n % 2 == 0) continue;
        try stdout.print("{d}\n", .{n});
    }
}
Output:
1
3
5
7
9