Sometimes, one may need   (or want)   a loop which
its   iterator   (the index
variable)   is modified within the

loop body    in addition to the normal incrementation by the   (do)   loop structure index.



Goal

Demonstrate the best way to accomplish this.



Task

Write a loop which:

   starts the index (variable) at   42
   (at iteration time)   increments the index by unity
   if the index is prime:
   displays the count of primes found (so far) and the prime   (to the terminal)
   increments the index such that the new index is now the (old) index plus that prime
   terminates the loop when   42   primes are shown


Extra credit:   because of the primes get rather large, use commas
within the displayed primes to ease comprehension.



Show all output here.



Note

Not all programming languages allow the modification of a
loop's index.   If that is the case, then use whatever method that
is appropriate or idiomatic for that language.   Please add a note
if the loop's index isn't modifiable.



Related tasks

   Loop over multiple arrays simultaneously
   Loops/Break
   Loops/Continue
   Loops/Do-while
   Loops/Downward for
   Loops/For
   Loops/For with a specified step
   Loops/Foreach
   Loops/Infinite
   Loops/N plus one half
   Loops/Nested
   Loops/While
   Loops/with multiple ranges
   Loops/Wrong ranges


Module LoopsIliwlb
 
    Sub Main()
        'Loops Increment loop index within loop body - 17/07/2018
        Dim imax, i As Int32
        Dim n As Int64
        imax = 42
        i = 0 : n = 42
        While i < imax
            If IsPrime(n) Then
                i = i + 1
                Console.WriteLine("i=" & RightX(i, 2) & " : " & RightX(Format(n, "#,##0"), 20))
                n = n + n - 1
            End If
            n = n + 1
        End While
    End Sub
 
    Function IsPrime(n As Int64)
        Dim i As Int64
        If n = 2 Or n = 3 Then
            IsPrime = True
        ElseIf (n Mod 2) = 0 Or (n Mod 3) = 0 Then
            IsPrime = False
        Else
            i = 5
            While i * i <= n
                If (n Mod i) = 0 Or (n Mod (i + 2)) = 0 Then
                    IsPrime = False
                    Exit Function
                End If
                i = i + 6
            End While
            IsPrime = True
        End If
    End Function 'IsPrime
 
    Function RightX(c, n)
        RightX = Right(Space(n) & c, n)
    End Function
 
End Module