Loops/For with a specified step: Difference between revisions

Content added Content deleted
(add E examples)
Line 81: Line 81:
(format t "~d, " i))
(format t "~d, " i))
(format t "who do we appreciate?~%")</lang>
(format t "who do we appreciate?~%")</lang>

=={{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. An ordinary while loop can of course be used:

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

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

<lang e>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?")</lang>

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 {
print(`$i, `)
}
println("who do we appreciate?")</lang>


=={{header|Forth}}==
=={{header|Forth}}==