Loops/Wrong ranges: Difference between revisions

(→‎{{header|Ruby}}: Added Ruby)
Line 1,010:
0 0 0 | 0,0,0,0,0,0,0,0,0,0,0,
Start equal stop equal zero: zero increment</pre>
 
=={{header|Visual Basic .NET}}==
'''Compiler:''' >= Visual Studio 2012
 
VB.NET's For loop accepts a starting and ending value and optional step.
 
Since the task mentions generators and a range of values, this implementation places the for loop in an iterator function (called a generator in many other languages) and yields the iteration variable in every iteration. The resulting IEnumerable object (whose actual class is generated by the compiler) is lazily-evaluated (i.e., it is run only when a new value is requested, and only until the next Yield statement).
 
The number of iterations is limited to 10 by the test code.
 
<lang vbnet>Module Program
Sub Main()
Example(-2, 2, 1, "Normal")
Example(-2, 2, 0, "Zero increment")
Example(-2, 2, -1, "Increments away from stop value")
Example(-2, 2, 10, "First increment is beyond stop value")
Example(2, -2, 1, "Start more than stop: positive increment")
Example(2, 2, 1, "Start equal stop: positive increment")
Example(2, 2, -1, "Start equal stop: negative increment")
Example(2, 2, 0, "Start equal stop: zero increment")
Example(0, 0, 0, "Start equal stop equal zero: zero increment")
End Sub
 
' Stop is a keyword and must be escaped using brackets.
Iterator Function Range(start As Integer, [stop] As Integer, increment As Integer) As IEnumerable(Of Integer)
For i = start To [stop] Step increment
Yield i
Next
End Function
 
Sub Example(start As Integer, [stop] As Integer, increment As Integer, comment As String)
' Add a space, pad to length 50 with hyphens, and add another space.
Console.Write((comment & " ").PadRight(50, "-"c) & " ")
 
Const MAX_ITER = 9
 
Dim iterations = 0
' The For Each loop enumerates the IEnumerable.
For Each i In Range(start, [stop], increment)
Console.Write("{0,2} ", i)
 
iterations += 1
If iterations > MAX_ITER Then Exit For
Next
 
Console.WriteLine()
End Sub
End Module</lang>
 
{{out}}
<pre>Normal ------------------------------------------- -2 -1 0 1 2
Zero increment ----------------------------------- -2 -2 -2 -2 -2 -2 -2 -2 -2 -2
Increments away from stop value ------------------
First increment is beyond stop value ------------- -2
Start more than stop: positive increment ---------
Start equal stop: positive increment ------------- 2
Start equal stop: negative increment ------------- 2
Start equal stop: zero increment ----------------- 2 2 2 2 2 2 2 2 2 2
Start equal stop equal zero: zero increment ------ 0 0 0 0 0 0 0 0 0 0</pre>
 
=={{header|zkl}}==
Anonymous user