Loops/For with a specified step

From Rosetta Code
Jump to: navigation, search
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

[edit] Ada

The FOR loop construct in Ada does not give the programmer the ability to directly modify the loop control variable during the execution of the loop. Instead, Ada automatically takes care of the modification of the loop control variable by incrementing it or decrementing it to be the next value in a specified discrete sequence. For this reason, in a "real" program, an Ada programmer would use a WHILE loop, or more likely a general LOOP, construct to perform this particular task. For the sake of this task, however, the following code demonstrates a way the task could be performed, when the range of loop control values is sufficiently small, through the definition of an enumeration type.

In the declarative section:

type Loop_Steps is (2, 4, 6, 8);

In the body section:

for Step in Loop_Steps loop
put(Step, 0);
put(", ");
end loop;
put("who do we appreciate?");

Another way to do this, which would be more practical for larger ranges, is to loop through all of the values in a range (even the ones we weren't interested in using) and use a conditional check to determine whether or not to use the current loop control variable at each iteration. This is rather inefficient, growing more so as the step values get larger, but it's still order of O(n). Again, this is purely academic, since an actual Ada programmer would rarely do something like this.

The following code prints multiples of three from 3 to 12:

for Value in 3 .. 12 loop
if Value mod 3 = 0 then
put(Value, 0);
put(", ")
end if;
end loop;
put("what's a word that rhymes with ""twelve""?");

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

[edit] AutoHotkey

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

[edit] AWK

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

[edit] BASIC

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

[edit] BBC BASIC

      FOR n = 2 TO 8 STEP 1.5
PRINT n
NEXT

Output:

         2
       3.5
         5
       6.5
         8

[edit] C

This prints all odd digits:

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

[edit] C++

This prints all odd digits:

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

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

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

[edit] Common Lisp

(loop for i from 2 to 8 by 2 do
(format t "~d, " i))
(format t "who do we appreciate?~%")

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

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

[edit] Dao

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

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

[edit] DWScript

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

Output:

2
4
6
8

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

[edit] Ela

open console
 
for m s n | n > m = ()
| else = writen n $ for m s (n+s)
 
for 10 2 0

Output:

0
2
4
6
8
10

[edit] Erlang

%% Implemented by Arjun Sunel
-module(loop_step).
-export([main/0, for_loop/1]).
 
% 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) when N < 4 ->
io:fwrite("* "),
for_loop(N+2);
 
for_loop(N) when N >= 4->
io:format("").
 
Output:
* * * * ok

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

[edit] Factor

Prints odd digits.

1 10 2 <range> [ . ] each

[edit] FALSE

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

[edit] Fantom

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

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

[edit] Forth

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

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

[edit] F#

for i in 2..2..8 do
printf "%d, " i
printfn "done"

Output:

2, 4, 6, 8, done

[edit] GML

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

[edit] Go

This prints all odd digits:

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

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

[edit] Haskell

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

[edit] HicEst

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

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

[edit] J

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

[edit] Java

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

[edit] JavaScript

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

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

[edit] Lang5

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

[edit] Liberty BASIC

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

[edit] Lisaac

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

[edit]

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

[edit] Lua

 
for i=2,9,2 do
print(i)
end
 

Output:

2
4
6
8

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

[edit] Mathematica

Do[
Print@i,
{i, 1, 20, 4}]

Output:

1
5
9
13
17

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

[edit] Maxima

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

[edit] МК-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.

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

[edit] Modula-3

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

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

[edit] Nemerle

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

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

[edit] Objeck

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

[edit] 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 = ()

[edit] Octave

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

[edit] Openscad

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

[edit] Oz

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

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

[edit] Pascal

See Delphi

[edit] Perl

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

[edit] Perl 6

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

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

[edit] PicoLisp

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

[edit] Pike

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

[edit] PL/I

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

[edit] PowerShell

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

[edit] PureBasic

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

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

[edit] R

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

[edit] Racket

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

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

[edit] REBOL

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

Output:

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


[edit] REXX

  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

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

Output

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

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

[edit] Salmon

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

[edit] SAS

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

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

[edit] Scala

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

Alternately:

 
(2 to 8 by 2) foreach println

[edit] Scheme

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

Output:

2
4
6
8

[edit] Seed7

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

[edit] Slate

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

[edit] Smalltalk

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

[edit] Tcl

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

[edit] TI-89 BASIC

Prints numbers from 0 to 100 stepping by 5.

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

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
LOOP i=2,9,2
PRINT i
ENDLOOP
 

Output:

2
4
6
8

[edit] UNIX Shell

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

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

[edit] C Shell

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

[edit] Vedit macro language

This prints all odd digits in range 1 to 9:

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

[edit] Vorpal

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

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

[edit] ZX Spectrum Basic

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

Variants
Actions
Community
Explore
Misc
Toolbox