Loops/For with a specified step: Difference between revisions
Zig version with for-loop added
(Bait solution) |
(Zig version with for-loop added) |
||
(4 intermediate revisions by one other user not shown) | |||
Line 1,546:
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.
<syntaxhighlight lang="
every 1 to 10 by 2 # the simplest case that satisfies the task, step by 2
every 1 to 10 # no
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
Line 2,043:
=={{header|Nim}}==
<syntaxhighlight lang="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
{{out}}
<pre>
1▼
5
6
9</pre>▼
7
8
9
5
6
7
8
0
4
8
12
16
16
12
8
4
0
=={{header|N/t/roff}}==
Line 2,632 ⟶ 2,672:
=={{header|Seed7}}==
<syntaxhighlight lang="
$ include "seed7_05.s7i";
const proc: main is func
Line 2,638 ⟶ 2,679:
var integer: number is 0;
begin
for number range
writeln(number);
end for;
writeln; # spacer
for number range 10 downto 0 step 2 do
writeln(number);
end for;
end func;
{{out}}
<pre>
0
2
4
6
8
10
10
8
6
4
2
0
</pre>
=={{header|Sidef}}==
Line 3,012 ⟶ 3,078:
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
pub fn main() !void {
Line 3,019 ⟶ 3,086:
while (i < 10) : (i += 2)
try stdout_wr.print("{d}\n", .{i});
}
▲}</syntaxhighlight>
</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>
|