Loops/For with a specified step

From Rosetta Code
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.

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

Contents

360 Assembly[edit]

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

Ada[edit]

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[edit]

Tested with Agena 2.9.5 Win32

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

Aime[edit]

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

ALGOL 60[edit]

 
FOR i:=5 UNTIL 25 STEP 5 DO
OUTINTEGER(i)
 


ALGOL 68[edit]

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[edit]

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

AppleScript[edit]

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

AutoHotkey[edit]

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

AWK[edit]

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

Axe[edit]

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

BASIC[edit]

Applesoft BASIC[edit]

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

Basic[edit]

Works with: QuickBasic version 4.5
FOR i = 2 TO 8 STEP 2
PRINT i; ", ";
NEXT i
PRINT "who do we appreciate?"

smart BASIC[edit]

-- Scott A. Rossell, 12-27-16

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

Commodore BASIC[edit]

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

Batch File[edit]

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

>

BBC BASIC[edit]

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

bc[edit]

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

Befunge[edit]

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

C[edit]

This prints all odd digits:

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

ChucK[edit]

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 >>>;
}
 

C++[edit]

This prints all odd digits:

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

C#[edit]

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?");
}
}

Ceylon[edit]

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

Clojure[edit]

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))

COBOL[edit]

       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[edit]

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

Common Lisp[edit]

 
(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?

Chapel[edit]

 
// 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

D[edit]

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[edit]

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

Delphi[edit]

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

DWScript[edit]

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

E[edit]

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?")

EchoLisp[edit]

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[edit]

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[edit]

#import extensions.
 
program =
[
2 to:8 &by:2 &doEach:i
[
console writeLine:i.
].
].

Elixir[edit]

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]

ERRE[edit]

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

Erlang[edit]

%% 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

Euphoria[edit]

 
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.

Factor[edit]

Prints odd digits.

1 10 2 <range> [ . ] each

FALSE[edit]

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

Fantom[edit]

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

FBSL[edit]

#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
 

FOCAL[edit]

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[edit]

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

Fortran[edit]

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

FreeBASIC[edit]

' FB 1.05.0 Win64
 
For i As Integer = 1 To 21 Step 2
Print i; " ";
Next
Print
Sleep
Output:
 1  3  5  7  9  11  13  15  17  19  21

F#[edit]

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

FutureBasic[edit]

 
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
 

Output:

Somewhere over the rainbow
Bluebirds fly.

Gambas[edit]

Public Sub Main()
Dim siCount As Short
 
For siCount = 1 To 50 Step 5
Print "Gambas is great!"
Next
 
End

GAP[edit]

  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
 

GML[edit]

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

Go[edit]

This prints all odd digits:

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

Groovy[edit]

"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[edit]

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

HicEst[edit]

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

Icon and Unicon[edit]

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 to, step is by 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.

Io[edit]

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

J[edit]

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

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:

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

Java[edit]

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

JavaScript[edit]

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[edit]

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[edit]

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

Kotlin[edit]

// 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[edit]

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.
LabVIEW Loops For with a specified step.png

Lang5[edit]

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


Lasso[edit]

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

Liberty BASIC[edit]

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

Lingo[edit]

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[edit]

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

LiveCode[edit]

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

[edit]

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

Lua[edit]

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

M4[edit]

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[edit]

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

Mathematica[edit]

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

MATLAB / Octave[edit]

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

A vectorized version of the code is

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

Maxima[edit]

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

MAXScript[edit]

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

Output:

 
0
2
4
6
8
10
OK
 

МК-61/52[edit]

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[edit]

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[edit]

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

MUMPS[edit]

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

NewLISP[edit]

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

Nim[edit]

for x in countdown(10,0,3): echo(x)
Output:
10
7
4
1

Nemerle[edit]

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

NetRexx[edit]

/* 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

Oberon-2[edit]

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[edit]

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

OCaml[edit]

# 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[edit]

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

Oforth[edit]

 1 100 2 step: i [ i println ]

Openscad[edit]

/* Loop from 3 to 9 in steps of 2 */
 
for ( l = [3:2:9] ) {
echo (l);
}
echo ("on a double white line.");

Oz[edit]

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

PARI/GP[edit]

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))

Panda[edit]

Panda doesn't nativly 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)

Pascal[edit]

See Delphi

Perl[edit]

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

Perl 6[edit]

Works with: Rakudo version 2010.07

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?';

Phix[edit]

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

PHP[edit]

<?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[edit]

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

Pike[edit]

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

PL/I[edit]

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

PowerShell[edit]

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

PureBasic[edit]

For i=-15 To 25 Step 5
Debug i
Next i

Python[edit]

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?

R[edit]

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[edit]

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

Raven[edit]

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[edit]

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


REXX[edit]

version 1[edit]

  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[edit]

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

output is the same as above.

Ring[edit]

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

Ruby[edit]

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?"
Output:
2, 4, 6, 8, who do we appreciate?

Run BASIC[edit]

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?

Rust[edit]

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

Prettier, but currently feature gated version (Rust 1.0)

Does not work in stable Rust

#![feature(step_by)]
 
fn main() {
for i in (2..8+1).step_by(2) {
print!("{}", i);
}
println!("who do we appreciate?!");
}

Additionally, there is a crate on crates.io called cfor which allows for the use of a C-like for loop.

 #[macro_use]
extern crate cfor;
 
fn main() {
cfor!(let mut i = 2; i <= 8; i+=2; {
println!("{}", i);
});
println!("Who do we appreciate?");
}

Salmon[edit]

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

SAS[edit]

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

Sather[edit]

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[edit]

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

Alternatively:

(2 to 8 by 2) foreach println

Scheme[edit]

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[edit]

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

Seed7[edit]

$ include "seed7_05.s7i";
 
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 10 step 2 do
writeln(number);
end for;
end func;

Sidef[edit]

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[edit]

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

Slate[edit]

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

Smalltalk[edit]

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

SSEM[edit]

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.

Swift[edit]

This prints all odd digits:

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

Alternately (removed in Swift 3):

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

Tcl[edit]

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

TI-83 BASIC[edit]

Prints numbers from 0 to 100 stepping by 5.

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

TI-89 BASIC[edit]

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

TorqueScript[edit]

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

TUSCRIPT[edit]

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

UNIX Shell[edit]

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

Bourne Shell[edit]

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

Korn Shell[edit]

Works with: Korn Shell
x=2
while [[$x -le 8]]; do
echo $x
((x=x+2))
done
Works with: Korn Shell
x=2
while ((x<=8)); do
echo $x
((x+=2))
done

Bourne Again Shell[edit]

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[edit]

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

Ursa[edit]

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

Vedit macro language[edit]

This prints all odd digits in range 1 to 9:

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

VBA[edit]

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

VBScript[edit]

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

Vim Script[edit]

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


Visual Basic[edit]

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[edit]

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 

Vorpal[edit]

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

Wart[edit]

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

XPL0[edit]

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[edit]

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})


ZX Spectrum Basic[edit]

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